Add WebAuthn MFA key support

This commit is contained in:
Jonathan Klabunde Tomer authored and Chris Eager committed 2026-09-14 10:48:37 -04:00
1 parent 2ee739dbe1
commit eb601cd51e
51 files changed
+2946 -260

No files matched your search

+6
View File
@@ -36,6 +36,12 @@
<groupId>org.eclipse.jetty.http2</groupId>
<artifactId>jetty-http2-client-transport</artifactId>
</dependency>
<dependency>
<groupId>com.webauthn4j</groupId>
<artifactId>webauthn4j-test</artifactId>
<version>${webauthn4j.version}</version>
</dependency>
</dependencies>
<build>
@@ -10,6 +10,14 @@ import static java.util.Objects.requireNonNull;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.io.Resources;
import com.google.common.net.HttpHeaders;
import com.webauthn4j.data.AuthenticatorAssertionResponse;
import com.webauthn4j.data.PublicKeyCredential;
import com.webauthn4j.data.PublicKeyCredentialDescriptor;
import com.webauthn4j.data.PublicKeyCredentialRequestOptions;
import com.webauthn4j.data.PublicKeyCredentialType;
import com.webauthn4j.data.UserVerificationRequirement;
import com.webauthn4j.data.client.challenge.DefaultChallenge;
import com.webauthn4j.test.client.ClientPlatform;
import io.dropwizard.configuration.ConfigurationValidationException;
import io.dropwizard.jersey.validation.Validators;
import io.grpc.ChannelCredentials;
@@ -33,6 +41,7 @@ import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
@@ -53,6 +62,7 @@ import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.signal.integration.config.Config;
import org.signal.integration.config.WebAuthnConfiguration;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
@@ -76,6 +86,7 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.mappers.MfaFailureExceptionMapper;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.CertificateUtil;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
@@ -113,6 +124,10 @@ public final class Operations {
);
}
public static WebAuthnConfiguration getWebAuthnConfiguration() {
return CONFIG.webAuthn();
}
public static TestUser registerNumberlessUser(final ReceiptCredential receiptCredential)
throws InvalidInputException, VerificationFailedException {
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
@@ -127,6 +142,7 @@ public final class Operations {
null,
receiptCredentialPresentation.serialize(),
null,
null,
user.accountAttributes(),
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
@@ -147,7 +163,7 @@ public final class Operations {
return user;
}
public static TestUser recoverNumberlessUser(final TestUser testUser, @Nullable final Integer totp) {
public static TestUser recoverNumberlessUserWithTotp(final TestUser testUser, @Nullable final Integer totp) {
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
final TestUser recoveredUser = TestUser.createNumberlessForRecovery(accountPassword, testUser.registrationPassword());
@@ -157,6 +173,79 @@ public final class Operations {
testUser.registrationPassword(),
null,
totp,
null,
recoveredUser.accountAttributes(),
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
generateSignedKEMPreKey(3, aciIdentityKeyPair),
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
Optional.empty(),
Optional.empty()));
final AccountIdentityResponse registrationResponse = apiPost("/v1/registration", registrationRequest)
// For a numberless account recovery, the username is the ACI
.authorized(testUser.aciUuid().toString(), accountPassword)
.executeExpectSuccess(AccountIdentityResponse.class);
recoveredUser.setAciUuid(registrationResponse.uuid());
return recoveredUser;
}
public static TestUser recoverNumberlessUserWithWebAuthn(final TestUser testUser,
final ClientPlatform clientPlatform,
final byte[] credentialId,
final String relyingPartyId) {
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
final TestUser recoveredUser = TestUser.createNumberlessForRecovery(accountPassword, testUser.registrationPassword());
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final RegistrationRequest initialRequest = new RegistrationRequest(null,
testUser.registrationPassword(),
null,
null,
null,
recoveredUser.accountAttributes(),
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
generateSignedKEMPreKey(3, aciIdentityKeyPair),
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
Optional.empty(),
Optional.empty()));
final Pair<Integer, MfaFailureExceptionMapper.MfaFailureResponse> initialResponse = apiPost("/v1/registration", initialRequest)
// For a numberless account recovery, the username is the ACI
.authorized(testUser.aciUuid().toString(), accountPassword)
.execute(MfaFailureExceptionMapper.MfaFailureResponse.class);
// we expect (and need) failure with status 441, which will contain the WebAuthn challenge
assert initialResponse.getLeft() == 441;
final MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = initialResponse.getRight();
assert mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
.stream()
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId));
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
clientPlatform.get(new PublicKeyCredentialRequestOptions(
new DefaultChallenge(mfaFailureResponse.webAuthnParameters().challenge()),
null,
relyingPartyId,
List.of(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, credentialId, null)),
UserVerificationRequirement.DISCOURAGED,
null));
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
testUser.registrationPassword(),
null,
null,
webAuthnVerificationResponseJson(credential),
recoveredUser.accountAttributes(),
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
@@ -192,6 +281,7 @@ public final class Operations {
registrationPassword,
null,
null,
null,
accountAttributes,
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
@@ -537,4 +627,34 @@ public final class Operations {
throw new RuntimeException(e);
}
}
/// Serializes an assertion into the [specification](https://www.w3.org/TR/webauthn/#dictdef-authenticationresponsejson) format.
static String webAuthnVerificationResponseJson(final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential) {
final AuthenticatorAssertionResponse response = credential.getResponse();
return """
{
"id": "%s",
"rawId": "%s",
"type": "public-key",
"clientExtensionResults": {},
"response": {
"clientDataJSON": "%s",
"authenticatorData": "%s",
"signature": "%s",
"userHandle": %s
}
}
""".formatted(
base64Url(credential.getRawId()),
base64Url(credential.getRawId()),
base64Url(response.getClientDataJSON()),
base64Url(response.getAuthenticatorData()),
base64Url(response.getSignature()),
response.getUserHandle() == null ? "null" : "\"" + base64Url(response.getUserHandle()) + "\"");
}
private static String base64Url(@Nullable final byte[] bytes) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
}
@@ -18,5 +18,6 @@ public record Config(@NotBlank String domain,
@NotBlank String prescribedRegistrationCode,
@NotBlank String prescribedReceiptSerial,
@NotBlank String prescribedReceiptCredential,
@NotBlank String serverZkPublicParams) {
@NotBlank String serverZkPublicParams,
@NotNull @Valid WebAuthnConfiguration webAuthn) {
}
@@ -0,0 +1,13 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.signal.integration.config;
import jakarta.validation.constraints.NotBlank;
public record WebAuthnConfiguration(
@NotBlank String relyingPartyId,
@NotBlank String origin) {
}
@@ -12,6 +12,23 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import com.eatthepath.otp.TimeBasedOneTimePasswordGenerator;
import com.google.protobuf.ByteString;
import com.webauthn4j.data.AttestationConveyancePreference;
import com.webauthn4j.data.AuthenticatorAttestationResponse;
import com.webauthn4j.data.AuthenticatorSelectionCriteria;
import com.webauthn4j.data.PublicKeyCredential;
import com.webauthn4j.data.PublicKeyCredentialCreationOptions;
import com.webauthn4j.data.PublicKeyCredentialParameters;
import com.webauthn4j.data.PublicKeyCredentialRpEntity;
import com.webauthn4j.data.PublicKeyCredentialType;
import com.webauthn4j.data.PublicKeyCredentialUserEntity;
import com.webauthn4j.data.ResidentKeyRequirement;
import com.webauthn4j.data.UserVerificationRequirement;
import com.webauthn4j.data.attestation.statement.COSEAlgorithmIdentifier;
import com.webauthn4j.data.client.Origin;
import com.webauthn4j.data.client.challenge.DefaultChallenge;
import com.webauthn4j.test.EmulatorUtil;
import com.webauthn4j.test.authenticator.webauthn.WebAuthnAuthenticatorAdaptor;
import com.webauthn4j.test.client.ClientPlatform;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
@@ -31,11 +48,16 @@ import org.junit.jupiter.api.Test;
import org.signal.chat.account.AccountsGrpc;
import org.signal.chat.account.ConfirmTotpKeyRequest;
import org.signal.chat.account.ConfirmTotpKeyResponse;
import org.signal.chat.account.FinishWebAuthnRegistrationRequest;
import org.signal.chat.account.FinishWebAuthnRegistrationResponse;
import org.signal.chat.account.GenerateTotpKeyRequest;
import org.signal.chat.account.GenerateTotpKeyResponse;
import org.signal.chat.account.ListMfaKeysRequest;
import org.signal.chat.account.ListMfaKeysResponse;
import org.signal.chat.account.StartWebAuthnRegistrationRequest;
import org.signal.chat.account.StartWebAuthnRegistrationResponse;
import org.signal.chat.account.TotpParameters;
import org.signal.integration.config.WebAuthnConfiguration;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.usernames.BaseUsernameException;
@@ -102,7 +124,7 @@ public class AccountTest {
assertEquals(ConfirmTotpKeyResponse.ResponseCase.KEY_CONFIRMED, confirmTotpKeyResponse.getResponseCase());
final int keyId = confirmTotpKeyResponse.getKeyConfirmed().getKeyId();
user = Operations.recoverNumberlessUser(user, totpGenerator.generateOneTimePassword(totpKey, Instant.now()));
user = Operations.recoverNumberlessUserWithTotp(user, totpGenerator.generateOneTimePassword(totpKey, Instant.now()));
assertEquals(user.aciUuid(), originalAci);
@@ -121,6 +143,69 @@ public class AccountTest {
}
}
@Test
public void testRecoverWithWebAuthn() throws VerificationFailedException, InvalidInputException {
final WebAuthnConfiguration webAuthnConfiguration = Operations.getWebAuthnConfiguration();
final ClientPlatform clientPlatform = new ClientPlatform(new Origin(webAuthnConfiguration.origin()), new WebAuthnAuthenticatorAdaptor(EmulatorUtil.NONE_ATTESTATION_AUTHENTICATOR));
final COSEAlgorithmIdentifier algorithm = COSEAlgorithmIdentifier.ES256;
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
TestUser user = Operations.registerNumberlessUser(receipt.credential());
final UUID originalAci = user.aciUuid();
try {
final StartWebAuthnRegistrationResponse startWebAuthnRegistrationResponse =
getAccountsStubForUser(user).startWebAuthnRegistration(StartWebAuthnRegistrationRequest.getDefaultInstance());
assertEquals(StartWebAuthnRegistrationResponse.ResponseCase.PARAMS, startWebAuthnRegistrationResponse.getResponseCase());
final StartWebAuthnRegistrationResponse.WebAuthnCreateParameters webAuthnCreateParameters = startWebAuthnRegistrationResponse.getParams();
assertTrue(
webAuthnCreateParameters.getAllowedAlgorithmsList().contains(algorithm.getValue()));
final PublicKeyCredential<AuthenticatorAttestationResponse, ?> credential =
clientPlatform.create(new PublicKeyCredentialCreationOptions(
new PublicKeyCredentialRpEntity(webAuthnConfiguration.relyingPartyId(), "test"),
new PublicKeyCredentialUserEntity(webAuthnCreateParameters.getUserHandle().toByteArray(), "test", "test"),
new DefaultChallenge(),
List.of(new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, algorithm)),
null,
List.of(),
new AuthenticatorSelectionCriteria(
null, false, ResidentKeyRequirement.DISCOURAGED, UserVerificationRequirement.DISCOURAGED),
AttestationConveyancePreference.NONE,
null));
final byte[] metadataCiphertext = Operations.randomBytes(160);
final FinishWebAuthnRegistrationResponse finishWebAuthnRegistrationResponse = getAccountsStubForUser(user)
.finishWebAuthnRegistration(FinishWebAuthnRegistrationRequest.newBuilder()
.setAttestationObject(ByteString.copyFrom(credential.getResponse().getAttestationObject()))
.setCollectedClientDataJsonBytes(ByteString.copyFrom(credential.getResponse().getClientDataJSON()))
.setMetadataCiphertext(ByteString.copyFrom(metadataCiphertext))
.build());
assertEquals(FinishWebAuthnRegistrationResponse.ResponseCase.KEY_CONFIRMED, finishWebAuthnRegistrationResponse.getResponseCase());
final int keyId = finishWebAuthnRegistrationResponse.getKeyConfirmed().getKeyId();
user = Operations.recoverNumberlessUserWithWebAuthn(user, clientPlatform, credential.getRawId(), webAuthnConfiguration.relyingPartyId());
assertEquals(originalAci, user.aciUuid());
// MFA key should remain set after re-registration
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> mfaKeys =
getAccountsStubForUser(user).listMfaKeys(ListMfaKeysRequest.getDefaultInstance()).getKeysMap();
assertEquals(1, mfaKeys.size());
assertTrue(mfaKeys.containsKey(keyId));
assertEquals(ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType.MFA_KEY_TYPE_WEBAUTHN, mfaKeys.get(keyId).getType());
assertArrayEquals(metadataCiphertext, mfaKeys.get(keyId).getMetadataCiphertext().toByteArray());
} finally {
Operations.deleteReceipt(receipt.serial());
Operations.deleteUser(user);
}
}
private static AccountsGrpc.AccountsBlockingStub getAccountsStubForUser(final TestUser user) {
return AccountsGrpc
.newBlockingStub(Operations.grpcChannel())
+1
View File
@@ -90,6 +90,7 @@
<stripe.version>33.4.0</stripe.version>
<swagger.version>2.2.54</swagger.version>
<testcontainers.version>2.0.5</testcontainers.version>
<webauthn4j.version>0.31.9.RELEASE</webauthn4j.version>
<!-- images to use in tests via testcontainers -->
<dynamodb.image>amazon/dynamodb-local:3.3.1@sha256:ff89bd48ff32cd8d9be5fee8873b65b8854dc408f1afe881be6eb00247bc0dab</dynamodb.image>
+2
View File
@@ -102,3 +102,5 @@ hlrLookup.apiKey: AAAAAAAAAAA
hlrLookup.apiSecret: AAAAAAAAAAA
foundationDbMessages.versionstampCipherKey.0: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
registrationWebAuthn.userHandleBlindingSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
+6
View File
@@ -572,3 +572,9 @@ foundationDbMessages:
- messages-1
- messages-2
- messages-3
registrationWebAuthn:
relyingPartyId: example.org
origin: https://example.org
challengeTtl: PT2M
userHandleBlindingSecret: secret://registrationWebAuthn.userHandleBlindingSecret
+12 -1
View File
@@ -22,7 +22,6 @@
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
<opentelemetry-logback-appender-1.0.version>2.31.1-alpha</opentelemetry-logback-appender-1.0.version>
<storekit.version>5.2.0</storekit.version>
<webauthn4j.version>0.31.9.RELEASE</webauthn4j.version>
</properties>
<dependencies>
@@ -58,6 +57,11 @@
<artifactId>webauthn4j-appattest</artifactId>
<version>${webauthn4j.version}</version>
</dependency>
<dependency>
<groupId>com.webauthn4j</groupId>
<artifactId>webauthn4j-core</artifactId>
<version>${webauthn4j.version}</version>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-jaxrs2-jakarta</artifactId>
@@ -572,6 +576,13 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.webauthn4j</groupId>
<artifactId>webauthn4j-test</artifactId>
<version>${webauthn4j.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.uuid</groupId>
<artifactId>java-uuid-generator</artifactId>
@@ -67,6 +67,7 @@ import org.whispersystems.textsecuregcm.configuration.TotpConfiguration;
import org.whispersystems.textsecuregcm.configuration.TurnConfiguration;
import org.whispersystems.textsecuregcm.configuration.UnidentifiedDeliveryConfiguration;
import org.whispersystems.textsecuregcm.configuration.VirtualThreadConfiguration;
import org.whispersystems.textsecuregcm.configuration.WebAuthnConfiguration;
import org.whispersystems.textsecuregcm.configuration.ZkConfig;
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
@@ -390,6 +391,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private TotpConfiguration registrationTotp = TotpConfiguration.DEFAULT;
@Valid
@NotNull
@JsonProperty
private WebAuthnConfiguration registrationWebAuthn;
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
return tlsKeyStore;
}
@@ -653,4 +659,8 @@ public class WhisperServerConfiguration extends Configuration {
public TotpConfiguration getRegistrationTotpConfiguration() {
return registrationTotp;
}
public WebAuthnConfiguration getRegistrationWebAuthnConfiguration() {
return registrationWebAuthn;
}
}
@@ -97,6 +97,7 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator
import org.whispersystems.textsecuregcm.auth.IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.auth.webauthn.WebAuthnCeremonyManager;
import org.whispersystems.textsecuregcm.auth.grpc.ProhibitAuthenticationInterceptor;
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
@@ -213,6 +214,7 @@ import org.whispersystems.textsecuregcm.mappers.IllegalStateExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.InvalidWebsocketAddressExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.MfaFailureExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
@@ -811,12 +813,19 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
changeNumberWaitingPeriods, config.getChangeNumber().postRegistrationWaitingPeriod(), clock);
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
final WebAuthnCeremonyManager webAuthnCeremonyManager = new WebAuthnCeremonyManager(
config.getRegistrationWebAuthnConfiguration().relyingPartyId(),
config.getRegistrationWebAuthnConfiguration().origin(),
config.getRegistrationWebAuthnConfiguration().challengeTtl(),
config.getRegistrationWebAuthnConfiguration().userHandleBlindingSecret().value(),
rateLimitersCluster);
final AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value(),
config.getRegistrationTotpConfiguration().maxValidationDelay());
config.getRegistrationTotpConfiguration().maxValidationDelay(),
webAuthnCeremonyManager);
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs, config.getRemoteConfigConfiguration().globalConfig());
APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), config.getApnConfiguration());
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
@@ -1389,7 +1398,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new SubscriptionExceptionMapper(),
new BackupExceptionMapper(),
new JsonMappingExceptionMapper(),
new RegistrationLockFailureExceptionMapper()
new RegistrationLockFailureExceptionMapper(),
new MfaFailureExceptionMapper()
).forEach(exceptionMapper -> {
environment.jersey().register(exceptionMapper);
webSocketEnvironment.jersey().register(exceptionMapper);
@@ -0,0 +1,29 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class MfaFailureException extends NoStackTraceException {
private final @Nullable AuthenticationCeremonyParameters webAuthnParameters;
private final boolean hasTotp;
public MfaFailureException(@Nullable AuthenticationCeremonyParameters webAuthnParameters, boolean hasTotpKey) {
this.webAuthnParameters = webAuthnParameters;
this.hasTotp = hasTotpKey;
}
public @Nullable AuthenticationCeremonyParameters getWebAuthnParameters() {
return webAuthnParameters;
}
public boolean hasTotpKey() {
return hasTotp;
}
}
@@ -0,0 +1,16 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth.webauthn;
import java.time.Duration;
import java.util.List;
/// Server-generated parameters for a freshly-initiated authentication ceremony.
public record AuthenticationCeremonyParameters(
byte[] challenge,
Duration timeout,
List<byte[]> allowedCredentialIds) {
}
@@ -0,0 +1,15 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth.webauthn;
import java.util.List;
/// Server-generated parameters for a freshly-initiated registration ceremony.
public record RegistrationCeremonyParameters(
byte[] userHandle,
List<Long> allowedAlgorithms,
List<byte[]> excludedCredentialIds) {
}
@@ -0,0 +1,17 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth.webauthn;
import com.webauthn4j.data.attestation.authenticator.AttestedCredentialData;
import com.webauthn4j.data.client.CollectedClientData;
/// Results of a registration ceremony for persisting.
public record RegistrationCeremonyResult(
AttestedCredentialData attestedCredentialData,
CollectedClientData collectedClientData,
long signCount
) {
}
@@ -0,0 +1,27 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth.webauthn;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import java.util.List;
public record WebAuthnAuthenticationParameters(
@Schema(description = "The authentication ceremony challenge.")
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
byte[] challenge,
@Schema(description = "The number of seconds the challenge will be valid.")
long timeoutSeconds,
@Schema(description = "A list of authenticators previously registered to the account.")
@JsonDeserialize(contentUsing = ByteArrayAdapter.Deserializing.class)
@JsonSerialize(contentUsing = ByteArrayAdapter.Serializing.class)
List<byte[]> allowedCredentialIds) {}
@@ -0,0 +1,231 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth.webauthn;
import com.google.common.annotations.VisibleForTesting;
import com.webauthn4j.WebAuthnManager;
import com.webauthn4j.credential.CredentialRecord;
import com.webauthn4j.data.AuthenticationData;
import com.webauthn4j.data.AuthenticationParameters;
import com.webauthn4j.data.PublicKeyCredentialParameters;
import com.webauthn4j.data.PublicKeyCredentialType;
import com.webauthn4j.data.RegistrationData;
import com.webauthn4j.data.RegistrationParameters;
import com.webauthn4j.data.RegistrationRequest;
import com.webauthn4j.data.attestation.statement.COSEAlgorithmIdentifier;
import com.webauthn4j.data.client.Origin;
import com.webauthn4j.server.ServerProperty;
import com.webauthn4j.util.exception.WebAuthnException;
import com.webauthn4j.verifier.exception.BadChallengeException;
import com.webauthn4j.verifier.exception.VerificationException;
import io.lettuce.core.SetArgs;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.HmacUtils;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import tools.jackson.core.JacksonException;
/// Handles WebAuthn registration and authentication operations.
public class WebAuthnCeremonyManager {
/// [relying party ID - WebAuthn TR](https://www.w3.org/TR/webauthn/#relying-party-identifier)
private final String rpId;
/// [origin - WebAuthn TR](https://www.w3.org/TR/webauthn/#dom-collectedclientdata-origin)
private final Origin origin;
private final byte[] blindingSecret;
private final Duration challengeTtl;
private final FaultTolerantRedisClusterClient challengeStorageCluster;
private final WebAuthnManager webAuthnManager;
private static final String RETRY_NAME = ResilienceUtil.name(WebAuthnCeremonyManager.class);
/// Ed25519 support is fairly limited, while ES256 is broadly supported
private static final List<PublicKeyCredentialParameters> ALLOWED_WEBAUTHN_CREDENTIAL_ALGORITHMS = List.of(
new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.Ed25519),
new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.ES256)
);
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
public WebAuthnCeremonyManager(final String rpId, final String origin, final Duration challengeTtl, final byte[] blindingSecret,
final FaultTolerantRedisClusterClient challengeStorageCluster) {
this.rpId = rpId;
this.origin = new Origin(origin);
this.challengeTtl = challengeTtl;
this.blindingSecret = blindingSecret;
this.challengeStorageCluster = challengeStorageCluster;
this.webAuthnManager = WebAuthnManager.createNonStrictWebAuthnManager();
}
/// Initiates a WebAuthn registration ceremony
///
/// @param identifier The account identifier
///
/// @param existingCredentials a list of already-stored credential records for the user; their IDs
/// will be provided to the client to help prevent registering a duplicate ID on the same
/// authenticator
///
/// @return parameters the client must use for its step in the registration ceremony. `identifier` will be blinded, so
/// that it is a [non-identifiable user handle](https://www.w3.org/TR/webauthn/#sctn-user-handle-privacy)
public RegistrationCeremonyParameters startRegistration(final UUID identifier, final List<? extends CredentialRecord> existingCredentials) {
return new RegistrationCeremonyParameters(
blindIdentifier(identifier),
ALLOWED_WEBAUTHN_CREDENTIAL_ALGORITHMS.stream().map(pkcp -> pkcp.getAlg().getValue()).toList(),
existingCredentials.stream().map(credentialRecord -> credentialRecord.getAttestedCredentialData().getCredentialId()).toList()
);
}
/// Verifies that the supplied authenticator response components form a
/// valid WebAuthn registration ceremony with acceptable parameters.
///
/// @param serializedAttestationObject the "attestation object" from the authenticator response,
/// serialized in the format specified by the WebAuthn TR. Its attestation format must be `none`
/// and any attestation statement must have been cleared to mitigate privacy risks.
///
/// @param collectedClientDataJson the "collected client data" from the authenticator response,
/// serialized in the [format specified by the WebAuthn TR](https://www.w3.org/TR/webauthn/#sctn-generating-an-attestation-object)
///
/// @return a record that can be stored for future authentication.
///
/// @throws WebAuthnException if the supplied authenticator response is
/// invalid for any reason (structurally or due to selecting unacceptable
/// parameters, for example an unsupported signature algorithm)
public RegistrationCeremonyResult verifyRegistration(
final byte[] serializedAttestationObject, final String collectedClientDataJson) throws WebAuthnException {
final RegistrationData registrationData;
try {
registrationData = webAuthnManager.parse(
new RegistrationRequest(serializedAttestationObject, collectedClientDataJson.getBytes(StandardCharsets.UTF_8)));
} catch (final JacksonException e) {
throw new WebAuthnException(e);
}
// These shouldn't ever be null, because the upstream RPC inputs are not nullable. However, the fields are annotated as
// nullable.
if (registrationData.getAttestationObject() == null) {
throw new WebAuthnException("Attestation object must not be null");
}
if (registrationData.getCollectedClientData() == null) {
throw new WebAuthnException("Collected client data must not be null");
}
if (!"none".equals(registrationData.getAttestationObject().getAttestationStatement().getFormat())) {
// Refuse any attestations; clients must clear them to prevent sharing information we don't want to store
throw new WebAuthnException("attestation format must be 'none'");
}
final ServerProperty serverProperties = ServerProperty.builder()
// we aren't verifying any signatures for registration, so we don't need to bother saving a
// challenge; accept whatever is supplied
.challenge(registrationData.getCollectedClientData().getChallenge())
.origin(origin)
.rpId(rpId)
.build();
webAuthnManager.verify(registrationData,
new RegistrationParameters(serverProperties, ALLOWED_WEBAUTHN_CREDENTIAL_ALGORITHMS, false, true));
return new RegistrationCeremonyResult(
registrationData.getAttestationObject().getAuthenticatorData().getAttestedCredentialData(),
registrationData.getCollectedClientData(),
registrationData.getAttestationObject().getAuthenticatorData().getSignCount());
}
/// Initiates a WebAuthn authentication ceremony.
///
/// Each call generates, and replaces any existing, [challenge](https://www.w3.org/TR/webauthn/#sctn-cryptographic-challenges).
///
/// @param identifier the identifier of the account to be authenticated
/// @param existingCredentials a list of stored credential records for the user being authenticated
///
/// @return a [AuthenticationCeremonyParameters] record with the details
/// needed by a client in possession of a matching authenticator to complete
/// the ceremony
public AuthenticationCeremonyParameters startAuthentication(final UUID identifier, List<? extends CredentialRecord> existingCredentials) {
final byte[] challengeKey = challengeKey(identifier);
final byte[] challenge = new byte[16];
SECURE_RANDOM.nextBytes(challenge);
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeRunnable(
() -> challengeStorageCluster.withBinaryCluster(cluster -> cluster.sync().set(challengeKey, challenge, SetArgs.Builder.ex(challengeTtl.toSeconds()))));
return new AuthenticationCeremonyParameters(
challenge,
challengeTtl,
existingCredentials.stream().map(cr -> cr.getAttestedCredentialData().getCredentialId()).toList());
}
/// Parses an authenticator response JSON blob, whose format is specified in the WebAuthn Technical Report
public AuthenticationData parseAuthenticationResponse(final String authenticationResponseJson) throws WebAuthnException {
try {
return webAuthnManager.parseAuthenticationResponseJSON(authenticationResponseJson);
} catch (final NullPointerException | JacksonException e) {
throw new WebAuthnException(e);
}
}
/// Verifies an authenticator response to a WebAuthn authentication ceremony, consuming any existing stored challenge.
///
/// If verification succeeds, the `CredentialRecord` is [updated in-place](https://www.w3.org/TR/webauthn-3/#authn-ceremony-update-credential-record).
///
/// @param identifier the identifier of the account to be authenticated
/// @param matchingCredential the stored credential record for the account to be authenticated with an ID matching the one from the authenticator response
/// @param authenticationData the parsed authenticator response
///
///
/// @throws VerificationException if the response could not be verified for any reason (incorrect signature, incorrect or expired challenge)
public void verifyAuthentication(
final UUID identifier,
final CredentialRecord matchingCredential,
final AuthenticationData authenticationData) throws VerificationException {
final byte[] challengeKey = challengeKey(identifier);
@Nullable final byte[] challenge = ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeSupplier(() -> challengeStorageCluster.withBinaryCluster(cluster -> cluster.sync().getdel(challengeKey)));
//noinspection ConstantValue
if (challenge == null) {
throw new BadChallengeException("no challenge stored");
}
final byte[] credentialId = matchingCredential.getAttestedCredentialData().getCredentialId();
final AuthenticationParameters authenticationParameters = new AuthenticationParameters(
ServerProperty.builder()
.origin(origin)
.rpId(rpId)
.challenge(() -> challenge)
.build(),
matchingCredential,
List.of(credentialId),
false,
true);
webAuthnManager.verify(authenticationData, authenticationParameters);
}
/// @return `true` if [CredentialRecord]s represent the same actual credential ID. Note that this is more specific than
/// whether they came from the same authenticator device, which cannot be determined in general.
public static boolean isSameCredential(final CredentialRecord a, final CredentialRecord b) {
return Arrays.equals(a.getAttestedCredentialData().getCredentialId(), b.getAttestedCredentialData().getCredentialId());
}
@VisibleForTesting
static byte[] challengeKey(final UUID identifier) {
return String.format("webauthn_challenge::{%s}", identifier).getBytes(StandardCharsets.UTF_8);
}
private byte[] blindIdentifier(final UUID identifier) {
return HmacUtils.hmac256Truncated(blindingSecret, UUIDUtil.toBytes(identifier), 32);
}
}
@@ -0,0 +1,19 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.util.ExactlySize;
public record WebAuthnConfiguration(
@NotBlank String relyingPartyId,
@NotBlank String origin,
@NotNull Duration challengeTtl,
@NotNull @ExactlySize(32) SecretBytes userHandleBlindingSecret) {
}
@@ -53,6 +53,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
import org.whispersystems.textsecuregcm.auth.MfaFailureException;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
@@ -66,10 +67,13 @@ import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.MfaFailureExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.AnnotatedTotpKey;
import org.whispersystems.textsecuregcm.storage.AnnotatedWebAuthnCredential;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo;
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
@@ -149,7 +153,12 @@ public class RegistrationController {
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@ApiResponse(responseCode = "441", description = "A valid one-time password (TOTP) is required, but either no password was provided or it was incorrect")
@ApiResponse(responseCode = "441",
description = """
Second factor authentication failed. Either the account has one or more factors configured, and the request’s
factor was incorrect or absent, or the account has no factors, but the request included a factor.
""",
content = @Content(schema = @Schema(implementation = MfaFailureExceptionMapper.MfaFailureResponse.class)))
@ApiResponse(responseCode = "499", description = "Client must support post-quantum ratchet")
public AccountCreationResponse register(
@Parameter(
@@ -171,7 +180,7 @@ public class RegistrationController {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@NotNull @Valid final RegistrationRequest registrationRequest,
@Context final ContainerRequestContext requestContext)
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException, MfaFailureException {
if (!registrationRequest.isEverySignedKeyValid(userAgent)) {
throw new WebApplicationException("Invalid signature", 422);
@@ -219,7 +228,7 @@ public class RegistrationController {
final ContainerRequestContext requestContext,
final String userAgent,
final String signalAgent)
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException, MfaFailureException {
if (registrationRequest.pniIdentityKey() == null) {
// RegistrationRequest checks that either all phone number-associated information is present or all is absent
@@ -249,7 +258,7 @@ public class RegistrationController {
// There can be at most one existing account for a set of numbers in the same equivalence class, so it's sufficient
// to find the first one.
final Optional<Account> existingAccount = Util.getAlternateForms(number)
Optional<Account> existingAccount = Util.getAlternateForms(number)
.stream()
.map(accounts::getByE164)
.filter(Optional::isPresent)
@@ -274,7 +283,7 @@ public class RegistrationController {
registrationRequest.accountAttributes().getRegistrationLock(),
userAgent, RegistrationLockVerificationManager.Flow.REGISTRATION, verificationType);
checkTotp(existingAccount.get(), registrationRequest.totp());
existingAccount = Optional.of(checkMfa(existingAccount.get(), registrationRequest.webAuthnResponse(), registrationRequest.totp()));
}
final Account account = accounts.create(number,
@@ -394,7 +403,7 @@ public class RegistrationController {
final String password,
final RegistrationRequest registrationRequest,
final String userAgent,
final String signalAgent) throws RegistrationLockFailureException, RateLimitExceededException {
final String signalAgent) throws RegistrationLockFailureException, RateLimitExceededException, MfaFailureException {
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
throw new BadRequestException("login purchases are not enabled");
@@ -412,7 +421,7 @@ public class RegistrationController {
throw new BadRequestException("Must specify a PNI-associated identity key when recovering an account by identifier");
}
final Account existingAccount = accounts.getByAccountIdentifier(accountIdentifier)
Account existingAccount = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(ForbiddenException::new);
final boolean passwordVerified = existingAccount.getAccountRecoveryPassword()
@@ -423,7 +432,7 @@ public class RegistrationController {
throw new ForbiddenException();
}
checkTotp(existingAccount, registrationRequest.totp());
existingAccount = checkMfa(existingAccount, registrationRequest.webAuthnResponse(), registrationRequest.totp());
if (!registrationRequest.skipDeviceTransfer() && existingAccount.hasCapability(DeviceCapability.TRANSFER)) {
// If a device transfer is possible, clients must explicitly opt out of a transfer (i.e. after prompting the user)
@@ -508,11 +517,39 @@ public class RegistrationController {
userAgent);
}
private void checkTotp(final Account account, @Nullable final Integer totp) throws RateLimitExceededException {
rateLimiters.getCheckTotpLimiter().validate(account.getAccountIdentifier());
/// @return the maybe-updated [Account] reference. Callers must use it to avoid stale reads and updates.
private Account checkMfa(final Account account, @Nullable final String webAuthn, @Nullable final Integer totp) throws RateLimitExceededException, MfaFailureException {
if (!accounts.verifyTotp(account, clock.instant(), totp)) {
throw new WebApplicationException(441);
final boolean hasTotp = account.getMfaKeys().values().stream().anyMatch(k -> k instanceof AnnotatedTotpKey);
final boolean hasWebAuthn = account.getMfaKeys().values().stream().anyMatch(k -> k instanceof AnnotatedWebAuthnCredential);
if (!hasTotp && !hasWebAuthn) {
if (totp != null || webAuthn != null) {
throw new MfaFailureException(null, false);
}
return account;
}
if (totp != null || webAuthn != null) {
rateLimiters.getCheckMfaLimiter().validate(account.getAccountIdentifier());
}
final Optional<Account> updatedAccount;
if (hasWebAuthn && webAuthn != null) {
updatedAccount = accounts.verifyWebAuthnAuthentication(account, webAuthn);
} else {
updatedAccount = Optional.empty();
}
final boolean webAuthnVerified = updatedAccount.isPresent();
final boolean totpVerified = hasTotp && totp != null
&& accounts.verifyTotp(account, clock.instant(), totp);
if (webAuthnVerified || totpVerified) {
return updatedAccount.orElse(account);
}
throw new MfaFailureException(accounts.startWebAuthnAuthentication(account).orElse(null), hasTotp);
}
}
@@ -14,10 +14,11 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
import java.util.List;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import jakarta.validation.constraints.PositiveOrZero;
import jakarta.validation.constraints.Size;
import org.apache.commons.lang3.ArrayUtils;
import org.signal.libsignal.protocol.IdentityKey;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
@@ -60,6 +61,15 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
@Nullable
Integer totp,
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
A JSON-serialized assertion response from a completed authentication ceremony.
See https://www.w3.org/TR/webauthn/#authenticatorassertionresponse.
""")
@Nullable
// There is no documented max size, but 8kiB should be enough
@Size(min = 1, max = 8192)
String webAuthnResponse,
@NotNull
@Valid
@Schema(requiredMode = Schema.RequiredMode.REQUIRED)
@@ -150,6 +160,13 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
@AssertTrue
@Schema(hidden = true)
boolean isMfaAbsentWhenUsingReceipt() {
return ArrayUtils.isEmpty(receiptCredentialPresentation) || totp == null;
return ArrayUtils.isEmpty(receiptCredentialPresentation) || (totp == null && webAuthnResponse == null);
}
@VisibleForTesting
@AssertTrue
@Schema(hidden = true)
boolean isAtMostOneMfaPresent() {
return totp == null || webAuthnResponse == null;
}
}
@@ -23,6 +23,7 @@ import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.signal.chat.account.Capabilities;
import org.signal.chat.account.ChangeNumberRequest;
import org.signal.chat.account.ChangeNumberResponse;
@@ -41,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.FinishWebAuthnRegistrationRequest;
import org.signal.chat.account.FinishWebAuthnRegistrationResponse;
import org.signal.chat.account.GenerateTotpKeyRequest;
import org.signal.chat.account.GenerateTotpKeyResponse;
import org.signal.chat.account.GetAccountDataReportRequest;
@@ -61,18 +64,21 @@ import org.signal.chat.account.ReserveUsernameHashRequest;
import org.signal.chat.account.ReserveUsernameHashResponse;
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
import org.signal.chat.account.SetDiscoverableByPhoneNumberResponse;
import org.signal.chat.account.SetMfaKeyMetadataRequest;
import org.signal.chat.account.SetMfaKeyMetadataResponse;
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.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;
import org.signal.chat.account.SetZkCredentialKeyResponse;
import org.signal.chat.account.SimpleAccountsGrpc;
import org.signal.chat.account.StaleDevices;
import org.signal.chat.account.StartWebAuthnRegistrationRequest;
import org.signal.chat.account.StartWebAuthnRegistrationResponse;
import org.signal.chat.account.StartWebAuthnRegistrationResponse.WebAuthnCreateParameters;
import org.signal.chat.account.TotpParameters;
import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
@@ -91,6 +97,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.RegistrationCeremonyParameters;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
@@ -107,6 +114,7 @@ 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.AnnotatedWebAuthnCredential;
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
@@ -121,7 +129,6 @@ import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import javax.annotation.Nullable;
public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@@ -616,6 +623,58 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
}
}
@Override
public StartWebAuthnRegistrationResponse startWebAuthnRegistration(final StartWebAuthnRegistrationRequest request) {
final Account account = getAuthenticatedAccount();
if (account.getNumber().isPresent()) {
throw GrpcExceptions.invalidArguments("WebAuthn keys may not be set for an account with a number");
}
try {
final RegistrationCeremonyParameters registrationParameters =
accountsManager.startWebAuthnRegistration(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
return StartWebAuthnRegistrationResponse.newBuilder()
.setParams(WebAuthnCreateParameters.newBuilder()
.setUserHandle(ByteString.copyFrom(registrationParameters.userHandle()))
.addAllAllowedAlgorithms(registrationParameters.allowedAlgorithms())
.addAllExcludeCredentialIds(
registrationParameters.excludedCredentialIds().stream().map(ByteString::copyFrom).toList()))
.build();
} catch (TooManyMfaKeysException _) {
return StartWebAuthnRegistrationResponse.newBuilder()
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
.build();
}
}
@Override
public FinishWebAuthnRegistrationResponse finishWebAuthnRegistration(final FinishWebAuthnRegistrationRequest request) {
final Account account = getAuthenticatedAccount();
if (account.getNumber().isPresent()) {
throw GrpcExceptions.invalidArguments("WebAuthn keys may not be set for an account with a number");
}
try {
final Optional<Byte> maybeKeyId = accountsManager.finishWebAuthnRegistration(
AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
request.getAttestationObject().toByteArray(),
request.getCollectedClientDataJson(),
request.getMetadataCiphertext().toByteArray());
return maybeKeyId.map(
keyId -> FinishWebAuthnRegistrationResponse.newBuilder()
.setKeyConfirmed(FinishWebAuthnRegistrationResponse.KeyConfirmed.newBuilder().setKeyId(keyId)))
.orElseGet(() -> FinishWebAuthnRegistrationResponse.newBuilder().setKeyNotConfirmed(FailedPrecondition.getDefaultInstance()))
.build();
} catch (TooManyMfaKeysException _) {
return FinishWebAuthnRegistrationResponse.newBuilder()
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
.build();
}
}
@Override
public ListMfaKeysResponse listMfaKeys(final ListMfaKeysRequest request) {
final ListMfaKeysResponse.Builder responseBuilder = ListMfaKeysResponse.newBuilder();
@@ -628,7 +687,8 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
ListMfaKeysResponse.MfaKeyMetadata.newBuilder()
.setMetadataCiphertext(ByteString.copyFrom(mfaKey.metadataCiphertext()))
.setType(switch (mfaKey) {
case AnnotatedTotpKey _ -> MfaKeyType.MFA_KEY_TYPE_TOTP;
case AnnotatedTotpKey _ -> MfaKeyType.MFA_KEY_TYPE_TOTP;
case AnnotatedWebAuthnCredential _ -> MfaKeyType.MFA_KEY_TYPE_WEBAUTHN;
}).build());
});
@@ -654,7 +714,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
});
return SetMfaKeyMetadataResponse.newBuilder()
.setMetadataUpdated(SetMfaKeyMetadataResponse.MetadataUpdated.getDefaultInstance())
.setSuccess(SetMfaKeyMetadataResponse.MetadataUpdated.getDefaultInstance())
.build();
} catch (final MfaKeyNotFoundException _) {
return SetMfaKeyMetadataResponse.newBuilder()
@@ -12,12 +12,13 @@ import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
import java.io.IOException;
import java.io.UncheckedIOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.storage.AccountNotFoundException;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
/**
* This interceptor observes responses from the service and if the response status is {@link Status#UNKNOWN}
@@ -52,6 +53,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
final StatusRuntimeException statusException = switch (cause) {
case ConvertibleToGrpcStatus e -> e.toStatusRuntimeException();
case AccountNotFoundException _ -> GrpcExceptions.invalidCredentials("invalid credentials");
case UncheckedIOException e -> {
log.warn("RPC {} encountered UncheckedIOException", call.getMethodDescriptor().getFullMethodName(), e.getCause());
yield GrpcExceptions.unavailable();
@@ -65,7 +65,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
CREATE_DONATION_PERMIT("createDonationCredential", new RateLimiterConfig(30, Duration.ofHours(4), true)),
ONE_TIME_DONATION("oneTimeDonation", new RateLimiterConfig(5, Duration.ofMinutes(1), true)),
ADD_SUBSCRIPTION_PAYMENT_METHOD("addSubscriptionPaymentMethod", new RateLimiterConfig(10, Duration.ofMinutes(1), true)),
CHECK_TOTP("checkTotp", new RateLimiterConfig(5, Duration.ofSeconds(6), false))
CHECK_MFA("checkMfa", new RateLimiterConfig(5, Duration.ofSeconds(6), false))
;
private final String id;
@@ -252,7 +252,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.CREATE_DONATION_PERMIT);
}
public RateLimiter getCheckTotpLimiter() {
return forDescriptor(For.CHECK_TOTP);
public RateLimiter getCheckMfaLimiter() {
return forDescriptor(For.CHECK_MFA);
}
}
@@ -0,0 +1,40 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.mappers;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.auth.MfaFailureException;
import org.whispersystems.textsecuregcm.auth.webauthn.WebAuthnAuthenticationParameters;
public class MfaFailureExceptionMapper implements ExceptionMapper<MfaFailureException> {
@Override
public Response toResponse(final MfaFailureException exception) {
return Response.status(441)
.entity(new MfaFailureResponse(
exception.getWebAuthnParameters() == null
? null
: new WebAuthnAuthenticationParameters(exception.getWebAuthnParameters().challenge(),
exception.getWebAuthnParameters().timeout().toSeconds(),
exception.getWebAuthnParameters().allowedCredentialIds()),
exception.hasTotpKey()))
.build();
}
@Schema(description = """
Information about the account's MFA status.
""")
public record MfaFailureResponse(
@Schema(description = "If the account has a WebAuthn credential, this field contains parameters for an authentication ceremony.")
@Nullable WebAuthnAuthenticationParameters webAuthnParameters,
@Schema(description = "Whether the account has a TOTP key configured")
boolean hasTotpKey) {
}
}
@@ -1,3 +1,8 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.mappers;
import jakarta.ws.rs.core.Response;
@@ -0,0 +1,14 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
/// An account was not found when it should have been (e.g. a previous lookup or authentication succeeded)
public class AccountNotFoundException extends RuntimeException {
public AccountNotFoundException() {
super();
}
}
@@ -12,6 +12,8 @@ import com.eatthepath.otp.TimeBasedOneTimePasswordGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.annotations.VisibleForTesting;
import com.webauthn4j.data.AuthenticationData;
import com.webauthn4j.util.exception.WebAuthnException;
import io.dropwizard.lifecycle.Managed;
import io.lettuce.core.RedisCommandTimeoutException;
import io.lettuce.core.RedisException;
@@ -43,6 +45,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.Queue;
@@ -59,6 +62,7 @@ import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
@@ -70,6 +74,10 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
import org.whispersystems.textsecuregcm.auth.webauthn.RegistrationCeremonyParameters;
import org.whispersystems.textsecuregcm.auth.webauthn.RegistrationCeremonyResult;
import org.whispersystems.textsecuregcm.auth.webauthn.WebAuthnCeremonyManager;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
@@ -148,6 +156,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final Duration maxTotpValidationDelay;
private final KeyGenerator totpKeyGenerator;
private final WebAuthnCeremonyManager webAuthnCeremonyManager;
private final Key verificationTokenKey;
@@ -283,6 +292,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
private static class UncheckedTooManyMfaKeysException extends NoStackTraceRuntimeException {
}
private static class UncheckedWebAuthnMismatchException extends NoStackTraceRuntimeException {
}
public AccountsManager(final Accounts accounts,
@@ -302,7 +314,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final ScheduledExecutorService retryExecutor,
final Clock clock,
final byte[] linkDeviceSecret,
final Duration maxTotpValidationDelay) {
final Duration maxTotpValidationDelay,
final WebAuthnCeremonyManager webAuthnCeremonyManager) {
this.accounts = accounts;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.cacheCluster = cacheCluster;
@@ -342,6 +355,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
throw new AssertionError("Every implementation of the Java platform is required to support the HmacSHA256 KeyGenerator algorithm", e);
}
this.webAuthnCeremonyManager = webAuthnCeremonyManager;
this.pubSubConnection = pubSubRedisClient.createPubSubConnection();
}
@@ -1037,7 +1051,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return true;
},
a -> accounts.changeNumber(a, targetNumber, targetPhoneNumberIdentifier, maybeDisplacedUuid, keyWriteItems),
() -> accounts.getByAccountIdentifier(uuid).orElseThrow(),
() -> accounts.getByAccountIdentifier(uuid).orElseThrow(AccountNotFoundException::new),
AccountChangeValidator.NUMBER_CHANGE_VALIDATOR);
}
@@ -1140,7 +1154,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
_ -> true,
a -> reservedUsernameHash.set(
checkAndReserveNextUsernameHash(a, new ArrayDeque<>(requestedUsernameHashes))),
() -> accounts.getByAccountIdentifier(account.getAccountIdentifier()).orElseThrow(),
() -> accounts.getByAccountIdentifier(account.getAccountIdentifier()).orElseThrow(AccountNotFoundException::new),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR);
redisDelete(updatedAccount);
@@ -1199,7 +1213,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final Account updatedAccount = updateWithRetries(
_ -> true,
a -> accounts.confirmUsernameHash(a, reservedUsernameHash, encryptedUsername),
() -> accounts.getByAccountIdentifier(account.getAccountIdentifier()).orElseThrow(),
() -> accounts.getByAccountIdentifier(account.getAccountIdentifier()).orElseThrow(AccountNotFoundException::new),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR);
redisDelete(updatedAccount);
@@ -1210,7 +1224,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
public Account clearUsernameHash(final UUID accountIdentifier) {
final Account updatedAccount = updateWithRetries(_ -> true,
accounts::clearUsernameHash,
() -> accounts.getByAccountIdentifier(accountIdentifier).orElseThrow(),
() -> accounts.getByAccountIdentifier(accountIdentifier).orElseThrow(AccountNotFoundException::new),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR);
redisDelete(updatedAccount);
@@ -1325,7 +1339,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final Account updatedAccount = updateWithRetries(updater,
persister,
() -> accounts.getByAccountIdentifier(accountIdentifier).orElseThrow(),
() -> accounts.getByAccountIdentifier(accountIdentifier).orElseThrow(AccountNotFoundException::new),
AccountChangeValidator.GENERAL_CHANGE_VALIDATOR);
redisSet(updatedAccount);
@@ -2169,10 +2183,159 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private boolean verifyTotp(final SecretKey totpKey, final Instant validationTimestamp, final int oneTimePassword) throws InvalidKeyException {
for (final Instant timestamp : new Instant[]{validationTimestamp, validationTimestamp.minus(maxTotpValidationDelay)}) {
if (TOTP.validateOneTimePassword(totpKey, timestamp, oneTimePassword)) {
return true;
}
if (TOTP.validateOneTimePassword(totpKey, timestamp, oneTimePassword)) {
return true;
}
}
return false;
}
/// Returns server-generated parameters needed to initiate a WebAuthn registration ceremony for the given account.
///
/// @param accountIdentifier the ACI of the account
///
/// @throws TooManyMfaKeysException if the account already has too many MFA keys registered
public RegistrationCeremonyParameters startWebAuthnRegistration(final UUID accountIdentifier)
throws TooManyMfaKeysException {
final Account account = getByAccountIdentifier(accountIdentifier).orElseThrow(AccountNotFoundException::new);
if (account.getMfaKeys().size() >= MAX_MFA_KEYS) {
throw new TooManyMfaKeysException();
}
return webAuthnCeremonyManager.startRegistration(accountIdentifier, getWebAuthnCredentials(account));
}
/// Verifies that the authenticator response for a WebAuthn registration ceremony is valid, then
/// stores the resulting credential in the account.
///
/// @param accountIdentifier the account with which to associate the new credential
/// @param serializedAttestationObject the "attestation object" from the authenticator response, serialized as specified in the WebAuthn TR
/// @param collectedClientDataJson the "collected client data" structure from the authenticator response, serialized as specified in the WebAuthn TR
/// @param metadataCiphertext encrypted user-provided metadata
/// @return the ID of the credential
public Optional<Byte> finishWebAuthnRegistration(
final UUID accountIdentifier,
final byte[] serializedAttestationObject,
final String collectedClientDataJson,
final byte[] metadataCiphertext) throws TooManyMfaKeysException {
try {
final RegistrationCeremonyResult registrationData = webAuthnCeremonyManager.verifyRegistration(
serializedAttestationObject, collectedClientDataJson);
final AnnotatedWebAuthnCredential newCredential = new AnnotatedWebAuthnCredential(
registrationData.attestedCredentialData(),
registrationData.signCount(),
metadataCiphertext);
final AtomicInteger keyId = new AtomicInteger();
update(
accountIdentifier,
account -> {
final Map<Byte, AnnotatedMfaKey> updatedMfaKeys = new HashMap<>(account.getMfaKeys());
final Optional<Byte> existingId = updatedMfaKeys.entrySet().stream()
.flatMap(idAndMfaKey -> {
if (idAndMfaKey.getValue() instanceof AnnotatedWebAuthnCredential credential) {
return Stream.of(new Pair<>(idAndMfaKey.getKey(), credential));
}
return Stream.empty();
})
.filter(idAndCredential -> WebAuthnCeremonyManager.isSameCredential(idAndCredential.second(), newCredential))
.map(Pair::first)
.findFirst();
if (existingId.isPresent()) {
keyId.set(existingId.get());
return false;
}
if (updatedMfaKeys.size() >= MAX_MFA_KEYS) {
throw new UncheckedTooManyMfaKeysException();
}
keyId.set(account.getNextMfaKeyId());
updatedMfaKeys.put((byte) keyId.get(), newCredential);
account.setMfaKeys(updatedMfaKeys);
return true;
});
return Optional.of((byte) keyId.get());
} catch (UncheckedTooManyMfaKeysException _) {
throw new TooManyMfaKeysException();
} catch (WebAuthnException _) {
return Optional.empty();
}
}
/// @return if a WebAuthn credential is registered to the account, parameters to start an authentication ceremony. Otherwise, empty.
public Optional<AuthenticationCeremonyParameters> startWebAuthnAuthentication(final Account account) {
final List<AnnotatedWebAuthnCredential> existingCredentials = getWebAuthnCredentials(account);
if (existingCredentials.isEmpty()) {
return Optional.empty();
}
return Optional.of(webAuthnCeremonyManager.startAuthentication(account.getAccountIdentifier(), existingCredentials));
}
/// @return the updated [Account], if verification succeeded. Otherwise, empty.
public Optional<Account> verifyWebAuthnAuthentication(final Account account, final String authenticationResponseJson) {
try {
final AuthenticationData authenticationData = webAuthnCeremonyManager.parseAuthenticationResponse(authenticationResponseJson);
final Map.Entry<Byte, AnnotatedMfaKey> matchingRecord = account.getMfaKeys().entrySet().stream()
.filter(mfaKey -> {
if (mfaKey.getValue() instanceof AnnotatedWebAuthnCredential credential) {
return Arrays.equals(authenticationData.getCredentialId(), credential.getCredentialId());
}
return false;
})
.findFirst()
.orElseThrow();
final AnnotatedWebAuthnCredential matchingCredential = (AnnotatedWebAuthnCredential) matchingRecord.getValue();
// The credential record's sign counter is updated in place as part of verification, and the stored challenge
// is consumed by the first call. To guard against concurrent updates, we have to both store the expected counter
// and verifyAuthentication() outside the idempotent update() consumer.
final long expectedCounter = matchingCredential.getCounter();
webAuthnCeremonyManager.verifyAuthentication(account.getAccountIdentifier(), matchingCredential, authenticationData);
final Account updatedAccount = update(account.getAccountIdentifier(), a -> {
final Map<Byte, AnnotatedMfaKey> updatedMfaKeys = new HashMap<>(a.getMfaKeys());
if (updatedMfaKeys.get(matchingRecord.getKey()) instanceof AnnotatedWebAuthnCredential credential
&& WebAuthnCeremonyManager.isSameCredential(credential, matchingCredential)
&& credential.getCounter() == expectedCounter) {
// Just in case there was a concurrent metadata update, use the stored credential's
final AnnotatedWebAuthnCredential mergedCredential = matchingCredential.withMetadataCiphertext(
credential.metadataCiphertext());
updatedMfaKeys.put(matchingRecord.getKey(), mergedCredential);
a.setMfaKeys(updatedMfaKeys);
} else {
// the counter changed or the key referenced by the ID changed. We could try to accommodate the latter,
// but it's an unlikely scenario, and we should just restart the ceremony.
throw new UncheckedWebAuthnMismatchException();
}
});
return Optional.of(updatedAccount);
} catch (WebAuthnException | NoSuchElementException | UncheckedWebAuthnMismatchException _) {
return Optional.empty();
}
}
private static List<AnnotatedWebAuthnCredential> getWebAuthnCredentials(final Account account) {
return account.getMfaKeys().values().stream()
.filter(AnnotatedWebAuthnCredential.class::isInstance)
.map(AnnotatedWebAuthnCredential.class::cast)
.toList();
}
}
@@ -9,8 +9,10 @@ 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 {
@JsonSubTypes({
@JsonSubTypes.Type(value=AnnotatedTotpKey.class, name = "totp"),
@JsonSubTypes.Type(value=AnnotatedWebAuthnCredential.class, name = "webauthn")})
public sealed interface AnnotatedMfaKey permits AnnotatedTotpKey, AnnotatedWebAuthnCredential {
byte[] metadataCiphertext();
AnnotatedMfaKey withMetadataCiphertext(byte[] newCiphertext);
}
@@ -0,0 +1,129 @@
/**
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.webauthn4j.credential.CredentialRecord;
import com.webauthn4j.data.attestation.authenticator.AttestedCredentialData;
import com.webauthn4j.data.client.CollectedClientData;
import java.util.Arrays;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
public final class AnnotatedWebAuthnCredential implements AnnotatedMfaKey, CredentialRecord {
@JsonSerialize(using = AttestedCredentialDataAdapter.Serializer.class)
@JsonDeserialize(using = AttestedCredentialDataAdapter.Deserializer.class)
private final AttestedCredentialData attestedCredentialData;
private long counter;
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
private final byte[] metadataCiphertext;
@JsonCreator
public AnnotatedWebAuthnCredential(
@JsonProperty("attestedCredentialData") final AttestedCredentialData attestedCredentialData,
@JsonProperty("counter") final long counter,
@JsonProperty("metadataCiphertext") final byte[] metadataCiphertext) {
this.attestedCredentialData = Objects.requireNonNull(attestedCredentialData);
this.counter = counter;
this.metadataCiphertext = metadataCiphertext;
}
@Override
public byte[] metadataCiphertext() {
return metadataCiphertext;
}
public byte[] getCredentialId() {
return attestedCredentialData.getCredentialId();
}
@Override
public AnnotatedWebAuthnCredential withMetadataCiphertext(final byte[] newMetadataCiphertext) {
return new AnnotatedWebAuthnCredential(attestedCredentialData, counter, newMetadataCiphertext);
}
/// Always `null` in this implementation
@Override
public Boolean isUvInitialized() {
return null;
}
@Nonnull
@Override
public AttestedCredentialData getAttestedCredentialData() {
return attestedCredentialData;
}
/// Always `null` in this implementation
@Nullable
@Override
public CollectedClientData getClientData() {
return null;
}
@Override
public long getCounter() {
return counter;
}
/// Always `null` in this implementation
@Override
public Boolean isBackupEligible() {
return null;
}
/// Always `null` in this implementation
@Override
public Boolean isBackedUp() {
return null;
}
@Override
public void setBackedUp(boolean backedUp) {
// not used in this implementation
}
@Override
public void setCounter(final long counter) {
this.counter = counter;
}
@Override
public void setUvInitialized(boolean uvInitialized) {
// not used in this implementation
}
@Override
public void setBackupEligible(boolean ignored) {
// not used in this implementation
}
@Override
public boolean equals(final Object o) {
if (!(o instanceof AnnotatedWebAuthnCredential that)) {
return false;
}
return counter == that.counter
&& Arrays.equals(metadataCiphertext, that.metadataCiphertext)
&& Objects.equals(attestedCredentialData, that.attestedCredentialData);
}
@Override
public int hashCode() {
return Objects.hash(attestedCredentialData, counter, Arrays.hashCode(metadataCiphertext));
}
}
@@ -0,0 +1,50 @@
/**
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.io.IOException;
import java.util.Base64;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.webauthn4j.converter.AttestedCredentialDataConverter;
import com.webauthn4j.converter.util.ObjectConverter;
import com.webauthn4j.data.attestation.authenticator.AttestedCredentialData;
public class AttestedCredentialDataAdapter {
private static final ObjectConverter OBJECT_CONVERTER = new ObjectConverter();
private static final AttestedCredentialDataConverter ATTESTED_CREDENTIAL_DATA_CONVERTER =
new AttestedCredentialDataConverter(OBJECT_CONVERTER);
public static class Serializer extends JsonSerializer<AttestedCredentialData> {
@Override
public void serialize(final AttestedCredentialData attestedCredentialData, final JsonGenerator jsonGenerator,
final SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeString(
Base64.getEncoder()
.withoutPadding()
.encodeToString(ATTESTED_CREDENTIAL_DATA_CONVERTER.convert(attestedCredentialData)));
}
}
public static class Deserializer extends JsonDeserializer<AttestedCredentialData> {
@Override
public AttestedCredentialData deserialize(final JsonParser jsonParser,
final DeserializationContext deserializationContext) throws IOException {
return ATTESTED_CREDENTIAL_DATA_CONVERTER.convert(Base64.getDecoder().decode(jsonParser.getValueAsString()));
}
}
}
@@ -1,14 +0,0 @@
/*
* Copyright 2021 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
public class RefreshingAccountNotFoundException extends RuntimeException {
public RefreshingAccountNotFoundException(final String message) {
super(message);
}
}
@@ -32,6 +32,7 @@ import org.whispersystems.textsecuregcm.WhisperServerService.ScheduledExecutorSe
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.auth.webauthn.WebAuthnCeremonyManager;
import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.BackupsDb;
import org.whispersystems.textsecuregcm.backup.Cdn3BackupCredentialGenerator;
@@ -367,12 +368,19 @@ public record CommandDependencies(
configuration.getDynamoDbTables().getChangeNumberWaitingPeriods().getTableName(), dynamoDbClient);
final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager = new ChangeNumberWaitingPeriodManager(
changeNumberWaitingPeriods, configuration.getChangeNumber().postRegistrationWaitingPeriod(), clock);
final WebAuthnCeremonyManager webAuthnCeremonyManager = new WebAuthnCeremonyManager(
configuration.getRegistrationWebAuthnConfiguration().relyingPartyId(),
configuration.getRegistrationWebAuthnConfiguration().origin(),
configuration.getRegistrationWebAuthnConfiguration().challengeTtl(),
configuration.getRegistrationWebAuthnConfiguration().userHandleBlindingSecret().value(),
rateLimitersCluster);
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
retryExecutor, clock, configuration.getLinkDeviceSecretConfiguration().secret().value(),
configuration.getRegistrationTotpConfiguration().maxValidationDelay());
configuration.getRegistrationTotpConfiguration().maxValidationDelay(),
webAuthnCeremonyManager);
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster, retryExecutor);
final BackupsDb backupsDb =
new BackupsDb(dynamoDbAsyncClient, configuration.getDynamoDbTables().getBackups().getTableName(), clock);
@@ -91,6 +91,16 @@ service Accounts {
// TOTP keys may only be generated for accounts without phone numbers.
rpc ConfirmTotpKey(ConfirmTotpKeyRequest) returns (ConfirmTotpKeyResponse) {}
// Returns parameters for initiating a WebAuthn registration ceremony
//
// WebAuthn credentials may only be registered for accounts without phone numbers
rpc StartWebAuthnRegistration(StartWebAuthnRegistrationRequest) returns (StartWebAuthnRegistrationResponse) {}
// Concludes a WebAuthn registration ceremony to add a passkey to the authenticated account
//
// WebAuthn credentials may only be registered for accounts without phone numbers
rpc FinishWebAuthnRegistration(FinishWebAuthnRegistrationRequest) returns (FinishWebAuthnRegistrationResponse) {}
// Returns a list of confirmed MFA keys for the authenticated account
rpc ListMfaKeys(ListMfaKeysRequest) returns (ListMfaKeysResponse) {}
@@ -575,6 +585,70 @@ message ConfirmTotpKeyResponse {
}
}
message StartWebAuthnRegistrationRequest {
}
message StartWebAuthnRegistrationResponse {
message WebAuthnCreateParameters {
// The "user handle" (user.id) that should be handed to the authenticator
bytes user_handle = 1;
// The COSE IDs (https://www.iana.org/assignments/cose#algorithms) of
// acceptable algorithms for the created key
repeated int64 allowed_algorithms = 2;
// A list of the credential IDs already registered for this account; these
// can be passed to candidate authenticators to tell them not to create a
// new key if they already have a private key matching one of these
repeated bytes exclude_credential_ids = 3;
}
oneof response {
// The parameters to use for a WebAuthn registration ceremony
WebAuthnCreateParameters params = 1;
// The authenticated account already has too many MFA keys, and the
// caller must remove one before adding one
errors.FailedPrecondition too_many_mfa_keys = 2 [(tag.reason) = "too_many_mfa_keys"];
}
}
message FinishWebAuthnRegistrationRequest {
// The attestation object from a completed registration ceremony, serialized
// as specified in https://www.w3.org/TR/webauthn/#attestation-object
bytes attestation_object = 1;
// The "collected client data" map used in the registration ceremony, as the
// exact JSON map that was hashed for the authenticator
string collected_client_data_json = 2;
// The ciphertext of user-provided metadata (presumably including a
// human-readable name and creation timestamp) to be attached to the
// newly-confirmed key
bytes metadata_ciphertext = 3 [(require.exactlySize) = 160];
}
message FinishWebAuthnRegistrationResponse {
message KeyConfirmed {
// An account-specific identifier for the new WebAuthn key
uint32 key_id = 1 [(require.range) = {min: 0, max: 127}];
}
oneof response {
// The provided public key has been registered for the account
KeyConfirmed key_confirmed = 1;
// The registration response was not verified successfully for any reason
errors.FailedPrecondition key_not_confirmed = 2 [(tag.reason) = "registration_ceremony_unsuccessful"];
// The authenticated account already has too many MFA keys, and the
// caller must remove one before adding one (this can be true even if it
// was not when starting the request, since there is nothing to prevent
// multiple registrations from occurring in parallel)
errors.FailedPrecondition too_many_mfa_keys = 3 [(tag.reason) = "too_many_mfa_keys"];
}
}
message ListMfaKeysRequest {}
message ListMfaKeysResponse {
@@ -582,12 +656,13 @@ message ListMfaKeysResponse {
enum MfaKeyType {
MFA_KEY_TYPE_UNSPECIFIED = 0;
MFA_KEY_TYPE_TOTP = 1;
MFA_KEY_TYPE_WEBAUTHN = 2;
}
/// The user-provided ciphertext for metadata associated with this MFA key
// The user-provided ciphertext for metadata associated with this MFA key
bytes metadata_ciphertext = 1 [(require.exactlySize) = 160];
/// The type of MFA factor this key is for
// The type of MFA factor this key is for
MfaKeyType type = 2;
}
@@ -608,8 +683,8 @@ message SetMfaKeyMetadataResponse {
}
oneof response {
// New metadata was stored for the identified TOTP key
MetadataUpdated metadata_updated = 1;
// New metadata was stored for the identified key
MetadataUpdated success = 1;
// No TOTP was found with the given ID
errors.NotFound key_not_found = 2 [(tag.reason) = "key_not_found"];
@@ -0,0 +1,391 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth.webauthn;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.webauthn4j.data.AttestationConveyancePreference;
import com.webauthn4j.data.AuthenticationData;
import com.webauthn4j.data.attestation.statement.COSEAlgorithmIdentifier;
import com.webauthn4j.data.client.challenge.DefaultChallenge;
import com.webauthn4j.test.EmulatorUtil;
import com.webauthn4j.util.exception.WebAuthnException;
import com.webauthn4j.verifier.exception.BadChallengeException;
import com.webauthn4j.verifier.exception.BadOriginException;
import com.webauthn4j.verifier.exception.BadRpIdException;
import com.webauthn4j.verifier.exception.VerificationException;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
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.ValueSource;
import org.whispersystems.textsecuregcm.auth.webauthn.WebAuthnTestHelper.TestRegistrationData;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.storage.AnnotatedWebAuthnCredential;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class WebAuthnCeremonyManagerTest {
@RegisterExtension
private static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
private static final String RP_ID = "example.org";
private static final String ORIGIN = "https://example.org";
private static final Duration CHALLENGE_TTL = Duration.ofMinutes(2);
private WebAuthnCeremonyManager webAuthnCeremonyManager;
private WebAuthnTestHelper helper;
@BeforeEach
void setUp() {
webAuthnCeremonyManager = new WebAuthnCeremonyManager(RP_ID, ORIGIN, CHALLENGE_TTL, TestRandomUtil.nextBytes(32),
REDIS_CLUSTER_EXTENSION.getRedisCluster());
helper = new WebAuthnTestHelper(RP_ID, ORIGIN, EmulatorUtil.NONE_ATTESTATION_AUTHENTICATOR);
}
/// Creates a [AnnotatedWebAuthnCredential] from the result with a random metadata ciphertext
private static AnnotatedWebAuthnCredential createCredential(final RegistrationCeremonyResult registrationResult) {
return new AnnotatedWebAuthnCredential(
registrationResult.attestedCredentialData(),
registrationResult.signCount(),
TestRandomUtil.nextBytes(160));
}
@Nested
class Registration {
@Test
void verifyRegistration() {
final RegistrationCeremonyParameters registrationParameters = webAuthnCeremonyManager.startRegistration(
UUID.randomUUID(), Collections.emptyList());
final TestRegistrationData regData = helper.register(registrationParameters);
final RegistrationCeremonyResult result = webAuthnCeremonyManager
.verifyRegistration(regData.serializedAttestationObject(), regData.collectedClientDataJson());
assertArrayEquals(regData.credentialId(), result.attestedCredentialData().getCredentialId());
assertEquals(ORIGIN, result.collectedClientData().getOrigin().toString());
}
@Test
void startRegistrationAdvertisesAllowedAlgorithms() {
final RegistrationCeremonyParameters parameters =
webAuthnCeremonyManager.startRegistration(UUID.randomUUID(), List.of());
assertEquals(
List.of(COSEAlgorithmIdentifier.Ed25519.getValue(), COSEAlgorithmIdentifier.ES256.getValue()),
parameters.allowedAlgorithms());
}
@Test
void startRegistrationExcludesExistingCredentials() {
final UUID identifier = UUID.randomUUID();
final TestRegistrationData firstRegData = helper.register(webAuthnCeremonyManager.startRegistration(identifier, List.of()));
final AnnotatedWebAuthnCredential firstCredential = createCredential(webAuthnCeremonyManager.verifyRegistration(
firstRegData.serializedAttestationObject(), firstRegData.collectedClientDataJson()));
final TestRegistrationData secondRegData = helper.register(webAuthnCeremonyManager.startRegistration(identifier, List.of()));
final AnnotatedWebAuthnCredential secondCredential = createCredential(webAuthnCeremonyManager.verifyRegistration(
secondRegData.serializedAttestationObject(), secondRegData.collectedClientDataJson()));
final RegistrationCeremonyParameters parameters =
webAuthnCeremonyManager.startRegistration(identifier, List.of(firstCredential, secondCredential));
assertEquals(2, parameters.excludedCredentialIds().size());
assertArrayEquals(firstCredential.getCredentialId(), parameters.excludedCredentialIds().getFirst());
assertArrayEquals(secondCredential.getCredentialId(), parameters.excludedCredentialIds().getLast());
}
@Test
void verifyRegistrationRejectsAttestation() {
final WebAuthnTestHelper helper = new WebAuthnTestHelper(RP_ID, ORIGIN, EmulatorUtil.PACKED_AUTHENTICATOR);
final byte[] userHandle = webAuthnCeremonyManager.startRegistration(UUID.randomUUID(), List.of()).userHandle();
final TestRegistrationData regData = helper.register(userHandle,
COSEAlgorithmIdentifier.ES256, new DefaultChallenge(), AttestationConveyancePreference.DIRECT);
assertThrows(WebAuthnException.class, () -> webAuthnCeremonyManager.verifyRegistration(
regData.serializedAttestationObject(), regData.collectedClientDataJson()));
}
@Test
void verifyRegistrationRejectsDisallowedAlgorithm() {
final byte[] userHandle = webAuthnCeremonyManager.startRegistration(UUID.randomUUID(), List.of()).userHandle();
final TestRegistrationData regData = helper.register(userHandle, COSEAlgorithmIdentifier.PS256);
assertThrows(WebAuthnException.class, () -> webAuthnCeremonyManager.verifyRegistration(
regData.serializedAttestationObject(), regData.collectedClientDataJson()));
}
@Test
void verifyRegistrationRejectsWrongOrigin() {
final WebAuthnTestHelper helper = new WebAuthnTestHelper(RP_ID, "https://not-signal.example.com",
EmulatorUtil.NONE_ATTESTATION_AUTHENTICATOR);
final TestRegistrationData regData = helper.register(webAuthnCeremonyManager.startRegistration(UUID.randomUUID(), List.of()));
assertThrows(BadOriginException.class, () -> webAuthnCeremonyManager.verifyRegistration(
regData.serializedAttestationObject(), regData.collectedClientDataJson()));
}
@Test
void verifyRegistrationRejectsWrongRpId() {
final WebAuthnTestHelper helper = new WebAuthnTestHelper("not-signal.example.com", ORIGIN,
EmulatorUtil.NONE_ATTESTATION_AUTHENTICATOR);
final TestRegistrationData regData = helper.register(webAuthnCeremonyManager.startRegistration(UUID.randomUUID(), List.of()));
assertThrows(BadRpIdException.class, () -> webAuthnCeremonyManager.verifyRegistration(
regData.serializedAttestationObject(), regData.collectedClientDataJson()));
}
@Test
void verifyRegistrationRejectsMalformedAttestationObject() {
final TestRegistrationData regData = helper.register(webAuthnCeremonyManager.startRegistration(UUID.randomUUID(), List.of()));
assertThrows(WebAuthnException.class, () -> webAuthnCeremonyManager.verifyRegistration(
TestRandomUtil.nextBytes(64), regData.collectedClientDataJson()));
}
@Test
void verifyRegistrationRejectsMalformedClientDataJson() {
final TestRegistrationData regData = helper.register(webAuthnCeremonyManager.startRegistration(UUID.randomUUID(), List.of()));
assertThrows(WebAuthnException.class, () -> webAuthnCeremonyManager.verifyRegistration(
regData.serializedAttestationObject(), "this is not json"));
}
}
@Nested
class Authentication {
private UUID identifier;
private AnnotatedWebAuthnCredential credential;
@BeforeEach
void setUp() {
identifier = UUID.randomUUID();
final TestRegistrationData regData = helper.register(webAuthnCeremonyManager.startRegistration(UUID.randomUUID(), List.of()));
credential = createCredential(webAuthnCeremonyManager.verifyRegistration(
regData.serializedAttestationObject(), regData.collectedClientDataJson()));
}
@Test
void startAuthenticationStoresChallenge() {
final AuthenticationCeremonyParameters parameters =
webAuthnCeremonyManager.startAuthentication(identifier, List.of(credential));
assertEquals(16, parameters.challenge().length);
assertEquals(CHALLENGE_TTL, parameters.timeout());
assertEquals(1, parameters.allowedCredentialIds().size());
assertArrayEquals(credential.getCredentialId(), parameters.allowedCredentialIds().getFirst());
final byte[] storedChallenge = REDIS_CLUSTER_EXTENSION.getRedisCluster()
.withBinaryCluster(cluster -> cluster.sync().get(WebAuthnCeremonyManager.challengeKey(identifier)));
assertArrayEquals(parameters.challenge(), storedChallenge);
final long ttlMillis = REDIS_CLUSTER_EXTENSION.getRedisCluster()
.withBinaryCluster(cluster -> cluster.sync().pttl(WebAuthnCeremonyManager.challengeKey(identifier)));
assertTrue(ttlMillis > 0 && ttlMillis <= CHALLENGE_TTL.toMillis(),
"Expected challenge TTL within " + CHALLENGE_TTL + ", but was " + Duration.ofMillis(ttlMillis));
}
@Test
void startAuthenticationReplacesPreviousChallenge() {
final byte[] firstChallenge = webAuthnCeremonyManager.startAuthentication(identifier, List.of(credential)).challenge();
final byte[] secondChallenge = webAuthnCeremonyManager.startAuthentication(identifier, List.of(credential)).challenge();
assertFalse(Arrays.equals(firstChallenge, secondChallenge));
final AuthenticationData staleAuthenticationData = webAuthnCeremonyManager.parseAuthenticationResponse(
helper.authenticate(credential.getCredentialId(), firstChallenge));
assertThrows(BadChallengeException.class,
() -> webAuthnCeremonyManager.verifyAuthentication(identifier, credential, staleAuthenticationData));
}
@Test
void verifyAuthentication() throws VerificationException {
final byte[] challenge = webAuthnCeremonyManager.startAuthentication(identifier, List.of(credential)).challenge();
final AuthenticationData authenticationData = webAuthnCeremonyManager.parseAuthenticationResponse(
helper.authenticate(credential.getCredentialId(), challenge));
assertArrayEquals(credential.getCredentialId(), authenticationData.getCredentialId());
final long preVerificationSignCount = credential.getCounter();
webAuthnCeremonyManager.verifyAuthentication(identifier, credential, authenticationData);
assertEquals(preVerificationSignCount + 1, credential.getCounter());
}
@Test
void verifyAuthenticationConsumesChallenge() throws VerificationException {
final byte[] challenge = webAuthnCeremonyManager.startAuthentication(identifier, List.of(credential)).challenge();
final AuthenticationData authenticationData = webAuthnCeremonyManager.parseAuthenticationResponse(
helper.authenticate(credential.getCredentialId(), challenge));
webAuthnCeremonyManager.verifyAuthentication(identifier, credential, authenticationData);
// Replaying the same assertion must fail; the challenge is consumed on first use
assertThrows(BadChallengeException.class,
() -> webAuthnCeremonyManager.verifyAuthentication(identifier, credential, authenticationData));
assertEquals(0L, REDIS_CLUSTER_EXTENSION.getRedisCluster()
.withBinaryCluster(cluster -> cluster.sync().exists(WebAuthnCeremonyManager.challengeKey(identifier))).longValue());
}
@Test
void verifyAuthenticationNoStoredChallenge() {
final AuthenticationData authenticationData = webAuthnCeremonyManager.parseAuthenticationResponse(
helper.authenticate(credential.getCredentialId(), TestRandomUtil.nextBytes(16)));
assertThrows(BadChallengeException.class,
() -> webAuthnCeremonyManager.verifyAuthentication(identifier, credential, authenticationData));
}
@Test
void verifyAuthenticationExpiredChallenge() {
final byte[] challenge = webAuthnCeremonyManager.startAuthentication(identifier, List.of(credential)).challenge();
final AuthenticationData authenticationData = webAuthnCeremonyManager.parseAuthenticationResponse(
helper.authenticate(credential.getCredentialId(), challenge));
// simulate expiration by deleting the challenge
assertEquals(1, (long) REDIS_CLUSTER_EXTENSION.getRedisCluster()
.withBinaryCluster(cluster -> cluster.sync().del(WebAuthnCeremonyManager.challengeKey(identifier))));
assertThrows(BadChallengeException.class,
() -> webAuthnCeremonyManager.verifyAuthentication(identifier, credential, authenticationData));
}
@Test
void verifyAuthenticationWrongChallenge() {
webAuthnCeremonyManager.startAuthentication(identifier, List.of(credential));
final AuthenticationData authenticationData = webAuthnCeremonyManager.parseAuthenticationResponse(
helper.authenticate(credential.getCredentialId(), TestRandomUtil.nextBytes(16)));
assertThrows(BadChallengeException.class,
() -> webAuthnCeremonyManager.verifyAuthentication(identifier, credential, authenticationData));
}
@Test
void verifyAuthenticationMismatchedCredential() {
final UUID identifier = UUID.randomUUID();
final TestRegistrationData firstRegData = helper.register(
webAuthnCeremonyManager.startRegistration(identifier, List.of()));
final AnnotatedWebAuthnCredential firstCredential = createCredential(webAuthnCeremonyManager.verifyRegistration(
firstRegData.serializedAttestationObject(), firstRegData.collectedClientDataJson()));
final TestRegistrationData secondRegData = helper.register(
webAuthnCeremonyManager.startRegistration(identifier, List.of()));
final AnnotatedWebAuthnCredential secondCredential = createCredential(webAuthnCeremonyManager.verifyRegistration(
secondRegData.serializedAttestationObject(), secondRegData.collectedClientDataJson()));
final byte[] challenge = webAuthnCeremonyManager.startAuthentication(identifier, List.of(firstCredential)).challenge();
final AuthenticationData authenticationData = webAuthnCeremonyManager.parseAuthenticationResponse(
helper.authenticate(secondCredential.getCredentialId(), challenge));
assertThrows(VerificationException.class,
() -> webAuthnCeremonyManager.verifyAuthentication(identifier, firstCredential, authenticationData),
"the second authenticator must not verify against the first credential");
}
@Test
void verifyAuthenticationBadSignature() {
final byte[] challenge = webAuthnCeremonyManager.startAuthentication(identifier, List.of(credential)).challenge();
final AuthenticationData authenticationData = webAuthnCeremonyManager.parseAuthenticationResponse(
helper.authenticateWithCorruptedSignature(credential.getCredentialId(), challenge));
assertThrows(VerificationException.class,
() -> webAuthnCeremonyManager.verifyAuthentication(identifier, credential, authenticationData));
}
@Test
void verifyAuthenticationWrongOrigin() {
final byte[] challenge = webAuthnCeremonyManager.startAuthentication(identifier, List.of(credential)).challenge();
final WebAuthnTestHelper wrongOrigin =
new WebAuthnTestHelper(RP_ID, "https://not-signal.example.com", EmulatorUtil.NONE_ATTESTATION_AUTHENTICATOR);
final TestRegistrationData incorrectOriginData = wrongOrigin.register(webAuthnCeremonyManager.startRegistration(identifier, List.of()));
final AuthenticationData authenticationData = webAuthnCeremonyManager.parseAuthenticationResponse(
wrongOrigin.authenticate(incorrectOriginData.credentialId(), challenge));
assertThrows(VerificationException.class,
() -> webAuthnCeremonyManager.verifyAuthentication(identifier, credential, authenticationData));
}
@ParameterizedTest
@ValueSource(strings = {
"this is not json",
"[]",
"\"qux\"",
"null",
"{}",
"""
{"id":"baz"}
""",
"""
{"id":"foo","rawId":"bar","type":"public-key","response":{}}
"""})
void parseAuthenticationResponseRejectsMalformedJson(final String authenticationResponseJson) {
assertThrows(WebAuthnException.class,
() -> webAuthnCeremonyManager.parseAuthenticationResponse(authenticationResponseJson));
}
@Test
void isSameCredential() {
final TestRegistrationData regData = helper.register(webAuthnCeremonyManager.startRegistration(identifier, List.of()));
final RegistrationCeremonyResult registrationResult = webAuthnCeremonyManager.verifyRegistration(
regData.serializedAttestationObject(), regData.collectedClientDataJson());
final AnnotatedWebAuthnCredential credential = createCredential(registrationResult);
// different stored metadata
final AnnotatedWebAuthnCredential sameCredential = createCredential(registrationResult);
// …and counter
sameCredential.setCounter(42);
final TestRegistrationData otherRegData = helper.register(
webAuthnCeremonyManager.startRegistration(identifier, List.of()));
final AnnotatedWebAuthnCredential otherCredential = createCredential(webAuthnCeremonyManager.verifyRegistration(
otherRegData.serializedAttestationObject(), otherRegData.collectedClientDataJson()));
// isSameCredential solely compares credentialId
assertTrue(WebAuthnCeremonyManager.isSameCredential(credential, sameCredential));
assertTrue(WebAuthnCeremonyManager.isSameCredential(credential, credential));
assertFalse(WebAuthnCeremonyManager.isSameCredential(credential, otherCredential));
assertNotEquals(credential, sameCredential, "same credential IDs with different counters are not equal");
}
}
}
@@ -0,0 +1,148 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth.webauthn;
import com.webauthn4j.data.AttestationConveyancePreference;
import com.webauthn4j.data.AuthenticatorAssertionResponse;
import com.webauthn4j.data.AuthenticatorAttestationResponse;
import com.webauthn4j.data.AuthenticatorSelectionCriteria;
import com.webauthn4j.data.PublicKeyCredential;
import com.webauthn4j.data.PublicKeyCredentialCreationOptions;
import com.webauthn4j.data.PublicKeyCredentialDescriptor;
import com.webauthn4j.data.PublicKeyCredentialParameters;
import com.webauthn4j.data.PublicKeyCredentialRequestOptions;
import com.webauthn4j.data.PublicKeyCredentialRpEntity;
import com.webauthn4j.data.PublicKeyCredentialType;
import com.webauthn4j.data.PublicKeyCredentialUserEntity;
import com.webauthn4j.data.ResidentKeyRequirement;
import com.webauthn4j.data.UserVerificationRequirement;
import com.webauthn4j.data.attestation.statement.COSEAlgorithmIdentifier;
import com.webauthn4j.data.client.Origin;
import com.webauthn4j.data.client.challenge.Challenge;
import com.webauthn4j.data.client.challenge.DefaultChallenge;
import com.webauthn4j.test.authenticator.webauthn.WebAuthnAuthenticator;
import com.webauthn4j.test.authenticator.webauthn.WebAuthnAuthenticatorAdaptor;
import com.webauthn4j.test.client.ClientPlatform;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import javax.annotation.Nullable;
class WebAuthnTestHelper {
private static final AuthenticatorSelectionCriteria AUTHENTICATOR_SELECTION = new AuthenticatorSelectionCriteria(
null, false, ResidentKeyRequirement.DISCOURAGED, UserVerificationRequirement.DISCOURAGED);
private final ClientPlatform clientPlatform;
private final String rpId;
TestRegistrationData register(RegistrationCeremonyParameters registrationParameters) {
// the webauthn4j emulator can only produce EC and RSA credentials, so Ed25519 isn't an option
return register(registrationParameters.userHandle(), COSEAlgorithmIdentifier.ES256);
}
/// Data a client uses to complete a registration ceremony.
record TestRegistrationData(byte[] serializedAttestationObject, String collectedClientDataJson, byte[] credentialId) {
}
WebAuthnTestHelper(final String rpId, final String origin, final WebAuthnAuthenticator authenticator) {
this.rpId = rpId;
this.clientPlatform = new ClientPlatform(new Origin(origin), new WebAuthnAuthenticatorAdaptor(authenticator));
}
TestRegistrationData register(final byte[] userHandle, final COSEAlgorithmIdentifier algorithm) {
return register(userHandle, algorithm, new DefaultChallenge(), AttestationConveyancePreference.NONE);
}
TestRegistrationData register(
final byte[] userHandle,
final COSEAlgorithmIdentifier algorithm,
final Challenge challenge,
final AttestationConveyancePreference attestationConveyancePreference) {
final PublicKeyCredential<AuthenticatorAttestationResponse, ?> credential =
clientPlatform.create(new PublicKeyCredentialCreationOptions(
new PublicKeyCredentialRpEntity(rpId, "test"),
new PublicKeyCredentialUserEntity(userHandle, "user", "user"),
challenge,
List.of(new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, algorithm)),
null,
List.of(),
AUTHENTICATOR_SELECTION,
attestationConveyancePreference,
null));
return new TestRegistrationData(
credential.getResponse().getAttestationObject(),
new String(credential.getResponse().getClientDataJSON(), StandardCharsets.UTF_8),
credential.getRawId());
}
/// Produces the JSON-serialized assertion response a client would send to conclude an authentication ceremony.
String authenticate(final byte[] credentialId, final byte[] challenge) {
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
clientPlatform.get(new PublicKeyCredentialRequestOptions(
new DefaultChallenge(challenge),
null,
rpId,
List.of(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, credentialId, null)),
UserVerificationRequirement.DISCOURAGED,
null));
return authenticationResponseJson(credential);
}
/// Produces an assertion response whose signature has been tampered with.
String authenticateWithCorruptedSignature(final byte[] credentialId, final byte[] challenge) {
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
clientPlatform.get(new PublicKeyCredentialRequestOptions(
new DefaultChallenge(challenge),
null,
rpId,
List.of(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, credentialId, null)),
UserVerificationRequirement.DISCOURAGED,
null));
final AuthenticatorAssertionResponse response = credential.getResponse();
final byte[] corruptedSignature = response.getSignature().clone();
corruptedSignature[corruptedSignature.length - 1] ^= 0xff;
return authenticationResponseJson(new PublicKeyCredential<>(
credential.getRawId(),
new AuthenticatorAssertionResponse(
response.getClientDataJSON(), response.getAuthenticatorData(), corruptedSignature, response.getUserHandle()),
credential.getClientExtensionResults()));
}
/// Serializes an assertion into the [specification](https://www.w3.org/TR/webauthn/#dictdef-authenticationresponsejson) format.
static String authenticationResponseJson(final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential) {
final AuthenticatorAssertionResponse response = credential.getResponse();
return """
{
"id": "%s",
"rawId": "%s",
"type": "public-key",
"clientExtensionResults": {},
"response": {
"clientDataJSON": "%s",
"authenticatorData": "%s",
"signature": "%s",
"userHandle": %s
}
}
""".formatted(
base64Url(credential.getRawId()),
base64Url(credential.getRawId()),
base64Url(response.getClientDataJSON()),
base64Url(response.getAuthenticatorData()),
base64Url(response.getSignature()),
response.getUserHandle() == null ? "null" : "\"" + base64Url(response.getUserHandle()) + "\"");
}
private static String base64Url(@Nullable final byte[] bytes) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
}
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.controllers;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@@ -22,6 +23,7 @@ import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.storage.ReceiptCredentialTestUtil.receiptPresentation;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
@@ -40,8 +42,10 @@ import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
@@ -54,11 +58,13 @@ import org.apache.http.HttpStatus;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
@@ -78,6 +84,7 @@ import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedE
import org.whispersystems.textsecuregcm.auth.RegistrationLockError;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicLoginPurchaseConfiguration;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
@@ -93,11 +100,15 @@ import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.MfaFailureExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
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.AnnotatedWebAuthnCredential;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo;
@@ -105,6 +116,7 @@ import org.whispersystems.textsecuregcm.storage.DeviceSpec;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.storage.ReceiptCredentialTestUtil;
import org.whispersystems.textsecuregcm.storage.TotpKey;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
@@ -147,6 +159,7 @@ class RegistrationControllerTest {
.addProvider(new RateLimitExceededExceptionMapper())
.addProvider(new ImpossiblePhoneNumberExceptionMapper())
.addProvider(new NonNormalizedPhoneNumberExceptionMapper())
.addProvider(new MfaFailureExceptionMapper())
.setMapper(SystemMapper.jsonMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(new RegistrationController(accountsManager, phoneVerificationTokenManager,
@@ -157,7 +170,7 @@ class RegistrationControllerTest {
@BeforeEach
void setUp() throws Exception {
when(rateLimiters.getRegistrationLimiter()).thenReturn(registrationLimiter);
when(rateLimiters.getCheckTotpLimiter()).thenReturn(totpLimiter);
when(rateLimiters.getCheckMfaLimiter()).thenReturn(totpLimiter);
when(accountsManager.update(any(UUID.class), any())).thenAnswer(invocation -> {
final Account account = invocation.getArgument(0);
@@ -419,6 +432,7 @@ class RegistrationControllerTest {
void totpInvalid() {
final Account existingAccount = mock(Account.class);
when(existingAccount.getNumber()).thenReturn(Optional.of(NUMBER));
when(existingAccount.getMfaKeys()).thenReturn(Map.of((byte) 1, new AnnotatedTotpKey(mock(TotpKey.class), new byte[0])));
when(accountsManager.getByE164(any())).thenReturn(Optional.of(existingAccount));
when(accountsManager.verifyTotp(any(), any(), any())).thenReturn(false);
@@ -435,30 +449,6 @@ class RegistrationControllerTest {
verify(accountsManager, never()).create(any(), any(), any(), any(), any(), any());
}
@Test
void totpRateLimited() throws RateLimitExceededException {
final Account existingAccount = mock(Account.class);
when(existingAccount.getAccountIdentifier()).thenReturn(UUID.randomUUID());
when(existingAccount.getNumber()).thenReturn(Optional.of(NUMBER));
when(accountsManager.getByE164(any())).thenReturn(Optional.of(existingAccount));
doThrow(new RateLimitExceededException(Duration.ofSeconds(5)))
.when(totpLimiter).validate(any(UUID.class));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
try (Response response = request.post(Entity.json(requestJson("sessionId", new byte[0], false, 1, 2)))) {
assertEquals(429, response.getStatus());
}
verify(accountsManager, never()).verifyTotp(any(), any(), any());
verify(accountsManager, never()).create(any(), any(), any(), any(), any(), any());
}
// this is functionally the same as deviceTransferAvailable(existingAccount=false)
@ParameterizedTest
@ValueSource(booleans = {true, false})
@@ -534,7 +524,9 @@ class RegistrationControllerTest {
new RegistrationRequest("session-id",
new byte[0],
null,
null, fetchesMessagesAccountAttributes,
null,
null,
fetchesMessagesAccountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
@@ -550,6 +542,7 @@ class RegistrationControllerTest {
new byte[0],
null,
null,
null,
fetchesMessagesAccountAttributes,
true,
aciIdentityKey,
@@ -566,6 +559,7 @@ class RegistrationControllerTest {
new byte[0],
null,
null,
null,
pushAccountAttributes,
true,
aciIdentityKey,
@@ -621,6 +615,7 @@ class RegistrationControllerTest {
new byte[0],
null,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -637,6 +632,7 @@ class RegistrationControllerTest {
new byte[0],
null,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -653,6 +649,7 @@ class RegistrationControllerTest {
new byte[0],
null,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -669,6 +666,7 @@ class RegistrationControllerTest {
new byte[0],
null,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -685,6 +683,7 @@ class RegistrationControllerTest {
new byte[0],
null,
null,
null,
accountAttributes,
true,
null,
@@ -701,6 +700,7 @@ class RegistrationControllerTest {
new byte[0],
null,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -781,6 +781,7 @@ class RegistrationControllerTest {
new byte[0],
receiptCredentialPresentation.serialize(),
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -858,6 +859,7 @@ class RegistrationControllerTest {
new byte[0],
receiptCredentialPresentation.serialize(),
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -902,6 +904,7 @@ class RegistrationControllerTest {
new byte[0],
receiptCredentialPresentation,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -965,6 +968,7 @@ class RegistrationControllerTest {
new byte[0],
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1).serialize(),
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1009,6 +1013,7 @@ class RegistrationControllerTest {
recoveryPassword,
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1).serialize(),
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1048,6 +1053,7 @@ class RegistrationControllerTest {
new byte[0],
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()).serialize(),
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1097,6 +1103,7 @@ class RegistrationControllerTest {
new byte[0],
receiptCredentialPresentation.serialize(),
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1133,6 +1140,7 @@ class RegistrationControllerTest {
new byte[0],
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()).serialize(),
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1182,6 +1190,7 @@ class RegistrationControllerTest {
new byte[0],
null,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1260,6 +1269,7 @@ class RegistrationControllerTest {
existingRecoveryPassword,
null,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1388,6 +1398,7 @@ class RegistrationControllerTest {
null,
null,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1407,6 +1418,7 @@ class RegistrationControllerTest {
null,
null,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1426,6 +1438,7 @@ class RegistrationControllerTest {
null,
TestRandomUtil.nextBytes(16),
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1445,6 +1458,7 @@ class RegistrationControllerTest {
existingRecoveryPassword,
null,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1464,6 +1478,7 @@ class RegistrationControllerTest {
existingRecoveryPassword,
null,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1483,6 +1498,7 @@ class RegistrationControllerTest {
TestRandomUtil.nextBytes(32),
null,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1502,6 +1518,7 @@ class RegistrationControllerTest {
existingRecoveryPassword,
null,
null,
null,
accountAttributes,
false,
aciIdentityKey,
@@ -1516,151 +1533,6 @@ class RegistrationControllerTest {
);
}
@Test
void recoverAccountInvalidTotp() {
final IdentityKey aciIdentityKey;
final IdentityKey pniIdentityKey;
final ECSignedPreKey aciSignedPreKey;
final ECSignedPreKey pniSignedPreKey;
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
{
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey());
pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey());
aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair);
pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair);
}
final byte[] deviceName = "test".getBytes(StandardCharsets.UTF_8);
final int registrationId = 1;
final int pniRegistrationId = 2;
final byte[] newRecoveryPassword = TestRandomUtil.nextBytes(32);
final Set<DeviceCapability> deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES;
final AccountAttributes accountAttributes =
new AccountAttributes(true, registrationId, pniRegistrationId, deviceName, null, false, deviceCapabilities, newRecoveryPassword)
.setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16));
final byte[] existingRecoveryPassword = TestRandomUtil.nextBytes(32);
final Account existingAccount = new Account();
existingAccount.setAccountIdentifier(UUID.randomUUID());
existingAccount.setAccountRecoveryPassword(existingRecoveryPassword);
when(accountsManager.getByAccountIdentifier(existingAccount.getAccountIdentifier()))
.thenReturn(Optional.of(existingAccount));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(existingAccount.getAccountIdentifier().toString(), PASSWORD));
when(accountsManager.verifyTotp(any(), any(), any()))
.thenReturn(false);
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
existingRecoveryPassword,
null,
null,
accountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
new DeviceActivationRequest(aciSignedPreKey,
Optional.of(pniSignedPreKey),
aciPqLastResortPreKey,
Optional.of(pniPqLastResortPreKey),
Optional.empty(),
Optional.empty()));
try (final Response response = request.post(Entity.json(requestToJson(registrationRequest)))) {
assertEquals(441, response.getStatus());
}
verify(accountsManager, never()).recover(any(), any(), any(), any(), any(), any());
verifyNoInteractions(phoneVerificationTokenManager);
}
@Test
void recoverAccountTotpRateLimited() throws RateLimitExceededException {
final IdentityKey aciIdentityKey;
final IdentityKey pniIdentityKey;
final ECSignedPreKey aciSignedPreKey;
final ECSignedPreKey pniSignedPreKey;
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
{
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey());
pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey());
aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair);
pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair);
}
final byte[] deviceName = "test".getBytes(StandardCharsets.UTF_8);
final int registrationId = 1;
final int pniRegistrationId = 2;
final byte[] newRecoveryPassword = TestRandomUtil.nextBytes(32);
final Set<DeviceCapability> deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES;
final AccountAttributes accountAttributes =
new AccountAttributes(true, registrationId, pniRegistrationId, deviceName, null, false, deviceCapabilities, newRecoveryPassword)
.setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16));
final byte[] existingRecoveryPassword = TestRandomUtil.nextBytes(32);
final Account existingAccount = new Account();
existingAccount.setAccountIdentifier(UUID.randomUUID());
existingAccount.setAccountRecoveryPassword(existingRecoveryPassword);
when(accountsManager.getByAccountIdentifier(existingAccount.getAccountIdentifier()))
.thenReturn(Optional.of(existingAccount));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(existingAccount.getAccountIdentifier().toString(), PASSWORD));
doThrow(new RateLimitExceededException(Duration.ofSeconds(5)))
.when(totpLimiter).validate(any(UUID.class));
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
existingRecoveryPassword,
null,
null,
accountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
new DeviceActivationRequest(aciSignedPreKey,
Optional.of(pniSignedPreKey),
aciPqLastResortPreKey,
Optional.of(pniPqLastResortPreKey),
Optional.empty(),
Optional.empty()));
try (final Response response = request.post(Entity.json(requestToJson(registrationRequest)))) {
assertEquals(429, response.getStatus());
}
verify(accountsManager, never()).verifyTotp(any(), any(), any());
verify(accountsManager, never()).recover(any(), any(), any(), any(), any(), any());
verifyNoInteractions(phoneVerificationTokenManager);
}
private static boolean accountAttributesEqual(final AccountAttributes a, final AccountAttributes b) {
return a.getFetchesMessages() == b.getFetchesMessages()
&& a.getRegistrationId() == b.getRegistrationId()
@@ -1755,6 +1627,7 @@ class RegistrationControllerTest {
new byte[0],
null,
null,
null,
fetchesMessagesAccountAttributes,
true,
aciIdentityKey,
@@ -1784,6 +1657,7 @@ class RegistrationControllerTest {
new byte[0],
null,
null,
null,
pushAccountAttributes,
true,
aciIdentityKey,
@@ -1812,6 +1686,7 @@ class RegistrationControllerTest {
new byte[0],
null,
null,
null,
pushAccountAttributes,
true,
aciIdentityKey,
@@ -1860,6 +1735,7 @@ class RegistrationControllerTest {
recoveryPassword,
null,
null,
null,
accountAttributes,
skipDeviceTransfer,
aciIdentityKey,
@@ -1931,4 +1807,299 @@ class RegistrationControllerTest {
}
""";
}
@Nested
class Mfa {
private static final String WEBAUTHN_RESPONSE = "{\"id\":\"credential\"}";
private static final int TOTP = 123456;
private static AnnotatedTotpKey totpKey() {
return new AnnotatedTotpKey(mock(TotpKey.class), new byte[0]);
}
private static AnnotatedWebAuthnCredential webAuthnCredential() {
return mock(AnnotatedWebAuthnCredential.class);
}
enum RegistrationPath {
REREGISTER_WITH_NUMBER(true),
RECOVER_NUMBERED(true),
RECOVER_NUMBERLESS(false);
private final boolean hasPhoneNumber;
RegistrationPath(final boolean hasPhoneNumber) {
this.hasPhoneNumber = hasPhoneNumber;
}
boolean isRecovery() {
return this != REREGISTER_WITH_NUMBER;
}
boolean hasPhoneNumber() {
return hasPhoneNumber;
}
}
private static final byte[] EXISTING_RECOVERY_PASSWORD = TestRandomUtil.nextBytes(32);
private static String mfaRequestJson(final RegistrationControllerTest.Mfa.RegistrationPath path,
@Nullable final Integer totp,
@Nullable final String webAuthnResponse) {
final boolean isRecovery = path.isRecovery();
final RegistrationRequest request = request(
isRecovery ? "" : "sessionId",
isRecovery ? Mfa.EXISTING_RECOVERY_PASSWORD : new byte[0],
true, 1, 2, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
final AccountAttributes accountAttributes = request.accountAttributes();
if (path.isRecovery()) {
// PNI-based registration recovery password isn't meaningfully different from re-registration via session
accountAttributes.setRecoveryPassword(TestRandomUtil.nextBytes(32));
}
return requestToJson(new RegistrationRequest(
request.sessionId(),
request.recoveryPassword(),
request.receiptCredentialPresentation(),
totp,
webAuthnResponse,
accountAttributes,
request.skipDeviceTransfer(),
request.aciIdentityKey(),
request.pniIdentityKey(),
request.deviceActivationRequest()));
}
private Account existingAccount(final boolean hasTotp, final boolean hasWebAuthn, final RegistrationPath path) {
final Map<Byte, AnnotatedMfaKey> mfaKeys = new HashMap<>();
if (hasTotp) {
mfaKeys.put((byte) 1, totpKey());
}
if (hasWebAuthn) {
mfaKeys.put((byte) 2, webAuthnCredential());
}
final Account account = new Account();
account.setAccountIdentifier(UUID.randomUUID());
account.setMfaKeys(mfaKeys);
if (path.hasPhoneNumber()) {
account.setNumber(NUMBER, UUID.randomUUID());
}
// a minimal, non-null, stub to return
final Account registeredAccount = mock(Account.class);
when(registeredAccount.getPrimaryDevice()).thenReturn(mock(Device.class));
if (path.isRecovery()) {
account.setAccountRecoveryPassword(EXISTING_RECOVERY_PASSWORD);
when(accountsManager.getByAccountIdentifier(account.getAccountIdentifier()))
.thenReturn(Optional.of(account));
when(accountsManager.recover(any(), any(), any(), any(), any(), any())).thenReturn(registeredAccount);
} else {
when(accountsManager.create(any(), any(), any(), any(), any(), any())).thenReturn(registeredAccount);
when(accountsManager.getByE164(any())).thenReturn(Optional.of(account));
}
return account;
}
private Response register(final Account existingAccount,
final RegistrationPath path,
@Nullable final Integer totp,
@Nullable final String webAuthnResponse) {
final String authHeader = path.isRecovery()
? AuthHelper.getAuthHeader(existingAccount.getAccountIdentifier(), PASSWORD)
: AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD);
return resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, authHeader)
.post(Entity.json(mfaRequestJson(path, totp, webAuthnResponse)));
}
static Stream<Arguments> checkMfa() {
record MfaCase(String name,
boolean hasTotp,
boolean hasWebAuthn,
@Nullable Integer totp,
@Nullable String webAuthnResponse,
boolean totpVerifies,
boolean webAuthnVerifies,
int expectedStatus) {
}
final List<MfaCase> cases = List.of(
// No MFA
new MfaCase("no mfa configured, none submitted, success", false, false, null, null, false, false, 200),
new MfaCase("no mfa configured, totp submitted, fails verification", false, false, TOTP, null, false, false, 441),
new MfaCase("no mfa configured, webauthn submitted, fails verification", false, false, null, WEBAUTHN_RESPONSE, false, false, 441),
// TOTP only
new MfaCase("has totp, totp submitted, success", true, false, TOTP, null, true, false, 200),
new MfaCase("has totp, totp submitted, fails verification", true, false, TOTP, null, false, false, 441),
new MfaCase("has totp, none submitted, fails", true, false, null, null, false, false, 441),
new MfaCase("has totp, webauthn submitted, fails", true, false, null, WEBAUTHN_RESPONSE, false, true, 441),
// WebAuthn only
new MfaCase("has webauthn, webauthn submitted, success", false, true, null, WEBAUTHN_RESPONSE, false, true, 200),
new MfaCase("has webauthn, webauthn submitted, fails verification", false, true, null, WEBAUTHN_RESPONSE, false, false, 441),
new MfaCase("has webauthn, none submitted, fails verification", false, true, null, null, false, false, 441),
new MfaCase("has webauthn, totp submitted, fails", false, true, TOTP, null, true, false, 441),
// Both
new MfaCase("both mfa configured, totp submitted, success", true, true, TOTP, null, true, false, 200),
new MfaCase("both mfa configured, webauthn submitted, success", true, true, null, WEBAUTHN_RESPONSE, false, true, 200),
new MfaCase("both mfa configured, totp submitted, fails verification", true, true, TOTP, null, false, false, 441),
new MfaCase("both mfa configured, webauth submitted, fails verification", true, true, null, WEBAUTHN_RESPONSE, false, false, 441),
new MfaCase("both mfa configured, none submitted, fails", true, true, null, null, false, false, 441));
return Arrays.stream(RegistrationPath.values())
.flatMap(path -> cases.stream()
.map(mfaCase -> Arguments.of(path,
mfaCase.hasTotp(),
mfaCase.hasWebAuthn(),
mfaCase.totp(),
mfaCase.webAuthnResponse(),
mfaCase.totpVerifies(),
mfaCase.webAuthnVerifies(),
mfaCase.expectedStatus())));
}
@ParameterizedTest
@MethodSource
void checkMfa(final RegistrationPath path,
final boolean hasTotp,
final boolean hasWebAuthn,
@Nullable final Integer totp,
@Nullable final String webAuthnResponse,
final boolean totpVerifies,
final boolean webAuthnVerifies,
final int expectedStatus) throws Exception {
final Account existingAccount = existingAccount(hasTotp, hasWebAuthn, path);
when(accountsManager.verifyTotp(any(), any(), any())).thenReturn(totpVerifies);
when(accountsManager.verifyWebAuthnAuthentication(any(), any()))
.thenReturn(webAuthnVerifies ? Optional.of(existingAccount) : Optional.empty());
final byte[] challenge = TestRandomUtil.nextBytes(16);
when(accountsManager.startWebAuthnAuthentication(any())).thenReturn(hasWebAuthn
? Optional.of(new AuthenticationCeremonyParameters(challenge, Duration.ofMinutes(2),
List.of(TestRandomUtil.nextBytes(32))))
: Optional.empty());
final JsonNode entity;
try (final Response response = register(existingAccount, path, totp, webAuthnResponse)) {
assertEquals(expectedStatus, response.getStatus());
entity = SystemMapper.jsonMapper().readTree(response.readEntity(String.class));
}
if (expectedStatus == 200) {
if (path.isRecovery()) {
verify(accountsManager).recover(any(), any(), any(), any(), any(), any());
} else {
verify(accountsManager).create(any(), any(), any(), any(), any(), any());
}
} else {
assertEquals(hasTotp, entity.get("hasTotpKey").asBoolean());
assertEquals(hasWebAuthn, entity.hasNonNull("webAuthnParameters"));
if (entity.hasNonNull("webAuthnParameters")) {
assertArrayEquals(challenge,
Base64.getDecoder().decode(entity.get("webAuthnParameters").get("challenge").asText()));
assertEquals(Duration.ofMinutes(2).toSeconds(),
entity.get("webAuthnParameters").get("timeoutSeconds").asLong());
}
verify(accountsManager, never()).create(any(), any(), any(), any(), any(), any());
verify(accountsManager, never()).recover(any(), any(), any(), any(), any(), any());
}
if (path.isRecovery()) {
verifyNoInteractions(phoneVerificationTokenManager);
}
}
@ParameterizedTest
@EnumSource(RegistrationPath.class)
void rateLimitedBeforeVerification(final RegistrationPath path) throws RateLimitExceededException {
final Account existingAccount = existingAccount(true, false, path);
doThrow(new RateLimitExceededException(Duration.ofSeconds(5)))
.when(totpLimiter).validate(any(UUID.class));
try (final Response response = register(existingAccount, path, TOTP, null)) {
assertEquals(429, response.getStatus());
}
verify(accountsManager, never()).verifyWebAuthnAuthentication(any(), any());
verify(accountsManager, never()).create(any(), any(), any(), any(), any(), any());
}
@ParameterizedTest
@EnumSource(RegistrationPath.class)
void bothFactorsPresentIsInvalid(final RegistrationPath path) {
final Account existingAccount = existingAccount(true, true, path);
try (final Response response = register(existingAccount, path, TOTP, WEBAUTHN_RESPONSE)) {
assertEquals(422, response.getStatus());
}
}
@ParameterizedTest
@EnumSource(RegistrationPath.class)
void oversizedWebAuthnResponseIsInvalid(final RegistrationPath path) {
final Account existingAccount = existingAccount(false, true, path);
try (final Response response = register(existingAccount, path, null, "x".repeat(8193))) {
assertEquals(422, response.getStatus());
}
}
@ParameterizedTest
@CsvSource({
"true, 429",
"false, 441"
})
void totpRateLimited(final boolean hasTotp, final int expectedStatus) throws RateLimitExceededException {
final Account existingAccount = mock(Account.class);
when(existingAccount.getAccountIdentifier()).thenReturn(UUID.randomUUID());
when(existingAccount.getNumber()).thenReturn(Optional.of(NUMBER));
when(accountsManager.getByE164(any())).thenReturn(Optional.of(existingAccount));
when(existingAccount.getMfaKeys()).thenReturn(
Map.of((byte) 1, new AnnotatedTotpKey(mock(TotpKey.class), new byte[0])));
doThrow(new RateLimitExceededException(Duration.ofSeconds(5)))
.when(totpLimiter).validate(any(UUID.class));
final Integer totp = hasTotp ? 987654 : null;
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
try (Response response = request.post(Entity.json(mfaRequestJson(RegistrationPath.REREGISTER_WITH_NUMBER, totp, null)))) {
assertEquals(expectedStatus, response.getStatus());
}
verify(accountsManager, never()).verifyTotp(any(), any(), any());
verify(accountsManager, never()).create(any(), any(), any(), any(), any(), any());
}
}
}
@@ -92,6 +92,7 @@ class RegistrationRequestTest {
null,
null,
null,
null,
true,
aciIdentityKey,
pniIdentityKey,
@@ -136,6 +137,7 @@ class RegistrationRequestTest {
null,
null,
null,
null,
new AccountAttributes(fetchesMessages, 1, 2, null, null, false, Collections.emptySet(), null),
true,
null,
@@ -163,6 +165,7 @@ class RegistrationRequestTest {
null,
null,
null,
null,
new AccountAttributes(true, 1, pniRegistrationIdPresent ? 2 : null, null, null, false, Collections.emptySet(), null),
true,
null,
@@ -183,12 +186,14 @@ class RegistrationRequestTest {
@CartesianTest
void isMfaAbsentWhenUsingReceipt(
@CartesianTest.Values(booleans = {false, true}) boolean hasWebAuthn,
@CartesianTest.Values(booleans = {false, true}) boolean hasTotp,
@CartesianTest.Values(booleans = {false, true}) boolean hasReceipt) {
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
null,
hasReceipt ? TestRandomUtil.nextBytes(32) : null,
hasTotp ? 12345 : null,
hasWebAuthn ? "{}" : null,
new AccountAttributes(true, 1, null, null, null, false, Collections.emptySet(), null),
true,
null,
@@ -200,7 +205,31 @@ class RegistrationRequestTest {
Optional.empty(),
Optional.empty()));
final boolean expectFailure = hasReceipt && hasTotp;
final boolean expectFailure = hasReceipt && (hasWebAuthn || hasTotp);
assertEquals(!expectFailure, registrationRequest.isMfaAbsentWhenUsingReceipt());
}
@CartesianTest
void atMostOneMfaPresent(
@CartesianTest.Values(booleans = {false, true}) boolean hasWebAuthn,
@CartesianTest.Values(booleans = {false, true}) boolean hasTotp) {
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
null,
null,
hasTotp ? 12345 : null,
hasWebAuthn ? "{}" : null,
new AccountAttributes(true, 1, null, null, null, false, Collections.emptySet(), null),
true,
null,
null,
new DeviceActivationRequest(null,
Optional.empty(),
null,
Optional.empty(),
Optional.empty(),
Optional.empty()));
final boolean expectFailure = hasWebAuthn && hasTotp;
assertEquals(!expectFailure, registrationRequest.isAtMostOneMfaPresent());
}
}
@@ -25,6 +25,10 @@ import static org.mockito.Mockito.when;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import com.webauthn4j.data.attestation.authenticator.AAGUID;
import com.webauthn4j.data.attestation.authenticator.AttestedCredentialData;
import com.webauthn4j.data.attestation.statement.COSEAlgorithmIdentifier;
import com.webauthn4j.test.TestDataUtil;
import io.grpc.Status;
import java.io.IOException;
import java.time.Duration;
@@ -63,6 +67,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.FinishWebAuthnRegistrationRequest;
import org.signal.chat.account.FinishWebAuthnRegistrationResponse;
import org.signal.chat.account.GenerateTotpKeyRequest;
import org.signal.chat.account.GenerateTotpKeyResponse;
import org.signal.chat.account.GetAccountDataReportRequest;
@@ -75,24 +81,25 @@ import org.signal.chat.account.GetEntitlementsRequest;
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.RegistrationLockFailure;
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.SetMfaKeyMetadataRequest;
import org.signal.chat.account.SetMfaKeyMetadataResponse;
import org.signal.chat.account.SetRegistrationLockRequest;
import org.signal.chat.account.SetRegistrationLockResponse;
import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
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;
import org.signal.chat.account.SetZkCredentialKeyResponse;
import org.signal.chat.account.StaleDevices;
import org.signal.chat.account.TotpParameters;
import org.signal.chat.account.StartWebAuthnRegistrationRequest;
import org.signal.chat.account.StartWebAuthnRegistrationResponse;
import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.account.ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType;
import org.signal.chat.common.AccountIdentifiers;
import org.signal.chat.common.EcSignedPreKey;
import org.signal.chat.common.KemSignedPreKey;
@@ -108,6 +115,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.RegistrationCeremonyParameters;
import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
@@ -123,16 +131,18 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountNotFoundException;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.AnnotatedMfaKey;
import org.whispersystems.textsecuregcm.storage.AnnotatedTotpKey;
import org.whispersystems.textsecuregcm.storage.AnnotatedWebAuthnCredential;
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
import org.whispersystems.textsecuregcm.storage.Device;
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.TooManyTotpKeysException;
import org.whispersystems.textsecuregcm.storage.TotpKey;
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
@@ -1230,7 +1240,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
}
@Test
void confirmTotpKeyTooManyNonTotpKeys() throws TooManyTotpKeysException, TooManyMfaKeysException {
void confirmTotpKeyTooManyNonTotpKeys() throws TooManyMfaKeysException {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
@@ -1266,15 +1276,15 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
.build()));
}
@Test
void listTotpKeys() {
final Map<Byte, AnnotatedMfaKey> totpKeys = Map.of(
void listMfaKeys() {
final Map<Byte, AnnotatedMfaKey> mfaKeys = Map.of(
(byte) 1, generateRandomAnnotatedTotpKey(),
(byte) 2, generateRandomAnnotatedTotpKey());
(byte) 2, generateRandomAnnotatedTotpKey(),
(byte) 3, generateRandomAnnotatedWebAuthnCredential());
final Account account = mock(Account.class);
when(account.getMfaKeys()).thenReturn(totpKeys);
when(account.getMfaKeys()).thenReturn(mfaKeys);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
@@ -1282,13 +1292,22 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final ListMfaKeysResponse response =
authenticatedServiceStub().listMfaKeys(ListMfaKeysRequest.getDefaultInstance());
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> expectedTotpKeys = totpKeys.entrySet().stream()
.collect(Collectors.toMap(entry -> entry.getKey().intValue(), entry -> ListMfaKeysResponse.MfaKeyMetadata.newBuilder()
.setType(MfaKeyType.MFA_KEY_TYPE_TOTP)
.setMetadataCiphertext(ByteString.copyFrom(entry.getValue().metadataCiphertext()))
.build()));
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> expectedMfaKeys = mfaKeys.entrySet().stream()
.collect(Collectors.toMap(entry -> entry.getKey().intValue(), entry -> {
final ListMfaKeysResponse.MfaKeyMetadata.Builder builder = ListMfaKeysResponse.MfaKeyMetadata.newBuilder()
.setMetadataCiphertext(ByteString.copyFrom(entry.getValue().metadataCiphertext()));
assertEquals(expectedTotpKeys, response.getKeysMap());
if (entry.getValue() instanceof AnnotatedTotpKey) {
builder.setType(MfaKeyType.MFA_KEY_TYPE_TOTP);
} else if (entry.getValue() instanceof AnnotatedWebAuthnCredential c) {
builder.setType(MfaKeyType.MFA_KEY_TYPE_WEBAUTHN);
}
return builder.build();
}));
assertEquals(expectedMfaKeys, response.getKeysMap());
}
@Test
@@ -1309,7 +1328,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
.setMetadataCiphertext(ByteString.copyFrom(updatedMetadata))
.build());
assertEquals(SetMfaKeyMetadataResponse.ResponseCase.METADATA_UPDATED, response.getResponseCase());
assertEquals(SetMfaKeyMetadataResponse.ResponseCase.SUCCESS, response.getResponseCase());
verify(account).setMfaKeys(Map.of(keyId, existingTotpKey.withMetadataCiphertext(updatedMetadata)));
}
@@ -1383,4 +1402,138 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
return new AnnotatedTotpKey(new TotpKey(TOTP_PARAMETERS, TestRandomUtil.nextBytes(32)),
TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE));
}
@Test
void startWebAuthnRegistration() throws TooManyMfaKeysException {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(account.getNumber()).thenReturn(Optional.empty());
final byte[] userHandle = TestRandomUtil.nextBytes(32);
final byte[] excludedCredentialId = TestRandomUtil.nextBytes(32);
when(accountsManager.startWebAuthnRegistration(AUTHENTICATED_ACI))
.thenReturn(new RegistrationCeremonyParameters(
userHandle, List.of(COSEAlgorithmIdentifier.ES256.getValue(), COSEAlgorithmIdentifier.Ed25519.getValue()), List.of(excludedCredentialId)));
final StartWebAuthnRegistrationResponse response =
authenticatedServiceStub().startWebAuthnRegistration(StartWebAuthnRegistrationRequest.getDefaultInstance());
assertEquals(StartWebAuthnRegistrationResponse.ResponseCase.PARAMS, response.getResponseCase());
assertArrayEquals(userHandle, response.getParams().getUserHandle().toByteArray());
assertEquals(List.of(COSEAlgorithmIdentifier.ES256.getValue(), COSEAlgorithmIdentifier.Ed25519.getValue()), response.getParams().getAllowedAlgorithmsList());
assertEquals(List.of(ByteString.copyFrom(excludedCredentialId)),
response.getParams().getExcludeCredentialIdsList());
}
@Test
void startWebAuthnRegistrationTooManyMfaKeys() throws TooManyMfaKeysException {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(account.getNumber()).thenReturn(Optional.empty());
when(accountsManager.startWebAuthnRegistration(AUTHENTICATED_ACI)).thenThrow(TooManyMfaKeysException.class);
final StartWebAuthnRegistrationResponse response =
authenticatedServiceStub().startWebAuthnRegistration(StartWebAuthnRegistrationRequest.getDefaultInstance());
assertEquals(StartWebAuthnRegistrationResponse.ResponseCase.TOO_MANY_MFA_KEYS, response.getResponseCase());
}
@Test
void startWebAuthnRegistrationAccountNotFound() throws TooManyMfaKeysException {
when(accountsManager.startWebAuthnRegistration(AUTHENTICATED_ACI)).thenThrow(AccountNotFoundException.class);
GrpcTestUtils.assertStatusException(Status.UNAUTHENTICATED,
() -> authenticatedServiceStub().startWebAuthnRegistration(StartWebAuthnRegistrationRequest.getDefaultInstance()));
}
@Test
void finishWebAuthnRegistration() throws TooManyMfaKeysException {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(account.getNumber()).thenReturn(Optional.empty());
final byte keyId = 42;
final byte[] attestationObject = TestRandomUtil.nextBytes(128);
final byte[] metadataCiphertext = TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE);
final String collectedClientDataJson = "{\"type\":\"webauthn.create\"}";
when(accountsManager.finishWebAuthnRegistration(
eq(AUTHENTICATED_ACI), any(), eq(collectedClientDataJson), any()))
.thenReturn(Optional.of(keyId));
final FinishWebAuthnRegistrationResponse response =
authenticatedServiceStub().finishWebAuthnRegistration(FinishWebAuthnRegistrationRequest.newBuilder()
.setAttestationObject(ByteString.copyFrom(attestationObject))
.setCollectedClientDataJson(collectedClientDataJson)
.setMetadataCiphertext(ByteString.copyFrom(metadataCiphertext))
.build());
assertEquals(FinishWebAuthnRegistrationResponse.ResponseCase.KEY_CONFIRMED, response.getResponseCase());
assertEquals(keyId, response.getKeyConfirmed().getKeyId());
verify(accountsManager).finishWebAuthnRegistration(
AUTHENTICATED_ACI, attestationObject, collectedClientDataJson, metadataCiphertext);
}
@Test
void finishWebAuthnRegistrationKeyNotConfirmed() throws TooManyMfaKeysException {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(account.getNumber()).thenReturn(Optional.empty());
when(accountsManager.finishWebAuthnRegistration(any(), any(), any(), any())).thenReturn(Optional.empty());
final FinishWebAuthnRegistrationResponse response =
authenticatedServiceStub().finishWebAuthnRegistration(FinishWebAuthnRegistrationRequest.newBuilder()
.setAttestationObject(ByteString.copyFrom(TestRandomUtil.nextBytes(128)))
.setCollectedClientDataJson("{}")
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE)))
.build());
assertEquals(FinishWebAuthnRegistrationResponse.ResponseCase.KEY_NOT_CONFIRMED, response.getResponseCase());
}
@Test
void finishWebAuthnRegistrationTooManyMfaKeys() throws TooManyMfaKeysException {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(account.getNumber()).thenReturn(Optional.empty());
when(accountsManager.finishWebAuthnRegistration(any(), any(), any(), any()))
.thenThrow(TooManyMfaKeysException.class);
final FinishWebAuthnRegistrationResponse response =
authenticatedServiceStub().finishWebAuthnRegistration(FinishWebAuthnRegistrationRequest.newBuilder()
.setAttestationObject(ByteString.copyFrom(TestRandomUtil.nextBytes(128)))
.setCollectedClientDataJson("{}")
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE)))
.build());
assertEquals(FinishWebAuthnRegistrationResponse.ResponseCase.TOO_MANY_MFA_KEYS, response.getResponseCase());
}
@Test
void finishWebAuthnRegistrationIncorrectMetadataSize() {
GrpcTestUtils.assertStatusInvalidArgument(
() -> authenticatedServiceStub().finishWebAuthnRegistration(FinishWebAuthnRegistrationRequest.newBuilder()
.setAttestationObject(ByteString.copyFrom(TestRandomUtil.nextBytes(128)))
.setCollectedClientDataJson("{}")
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE + 1)))
.build()));
}
private static AnnotatedWebAuthnCredential generateRandomAnnotatedWebAuthnCredential() {
return new AnnotatedWebAuthnCredential(
new AttestedCredentialData(AAGUID.ZERO, TestRandomUtil.nextBytes(32), TestDataUtil.createEC2COSEPublicKey()),
0,
TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE));
}
}
@@ -0,0 +1,80 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.mappers;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.ws.rs.core.Response;
import java.time.Duration;
import java.util.Collection;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.auth.MfaFailureException;
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
import org.whispersystems.textsecuregcm.auth.webauthn.WebAuthnAuthenticationParameters;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class MfaFailureExceptionMapperTest {
private MfaFailureExceptionMapper mapper;
@BeforeEach
void setUp() {
mapper = new MfaFailureExceptionMapper();
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void totp(final boolean hasTotpKey) throws JsonProcessingException {
try (final Response response = mapper.toResponse(new MfaFailureException(null, hasTotpKey))) {
assertEquals(441, response.getStatus());
final MfaFailureExceptionMapper.MfaFailureResponse entity = (MfaFailureExceptionMapper.MfaFailureResponse) response.getEntity();
assertNull(entity.webAuthnParameters());
assertEquals(hasTotpKey, entity.hasTotpKey());
}
}
@ParameterizedTest
@MethodSource
void webAuthn(final byte[] challenge, final List<byte[]> credentialIds) {
try (final Response response = mapper.toResponse(new MfaFailureException(
new AuthenticationCeremonyParameters(challenge, Duration.ofMinutes(2),credentialIds), false))) {
final MfaFailureExceptionMapper.MfaFailureResponse entity = (MfaFailureExceptionMapper.MfaFailureResponse) response.getEntity();
assertFalse(entity.hasTotpKey());
assertNotNull(entity.webAuthnParameters());
final WebAuthnAuthenticationParameters webAuthnParameters = entity.webAuthnParameters();
assertArrayEquals(challenge, webAuthnParameters.challenge());
assertEquals(Duration.ofMinutes(2).toSeconds(), webAuthnParameters.timeoutSeconds());
assertEquals(
credentialIds,
webAuthnParameters.allowedCredentialIds());
}
}
static Collection<Arguments> webAuthn() {
return List.of(
Arguments.argumentSet("no credentials", TestRandomUtil.nextBytes(16), List.of()),
Arguments.argumentSet("one credential", TestRandomUtil.nextBytes(16), List.of(TestRandomUtil.nextBytes(32))),
Arguments.argumentSet("two credentials", TestRandomUtil.nextBytes(16), List.of(TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32)))
);
}
}
@@ -175,7 +175,8 @@ public class AccountCreationDeletionIntegrationTest {
executor,
CLOCK,
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2));
AccountsManager.TOTP.getTimeStep().dividedBy(2),
null);
}
@AfterEach
@@ -155,7 +155,8 @@ class AccountsManagerChangeNumberIntegrationTest {
executor,
mock(Clock.class),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2));
AccountsManager.TOTP.getTimeStep().dividedBy(2),
null);
}
}
@@ -136,7 +136,8 @@ class AccountsManagerConcurrentModificationIntegrationTest {
mock(ScheduledExecutorService.class),
mock(Clock.class),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2)
AccountsManager.TOTP.getTimeStep().dividedBy(2),
null
);
}
}
@@ -71,7 +71,8 @@ public class AccountsManagerDeviceTransferIntegrationTest {
mock(ScheduledExecutorService.class),
Clock.systemUTC(),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2));
AccountsManager.TOTP.getTimeStep().dividedBy(2),
null);
accountsManager.start();
}
@@ -141,7 +141,8 @@ public class AccountsManagerMigrateRecoveryPasswordIntegrationTest {
executor,
mock(Clock.class),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2));
AccountsManager.TOTP.getTimeStep().dividedBy(2),
null);
}
}
@@ -9,6 +9,7 @@ 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.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -34,6 +35,14 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.webauthn4j.data.AuthenticationData;
import com.webauthn4j.data.attestation.authenticator.AAGUID;
import com.webauthn4j.data.attestation.authenticator.AttestedCredentialData;
import com.webauthn4j.data.attestation.statement.COSEAlgorithmIdentifier;
import com.webauthn4j.test.TestDataUtil;
import com.webauthn4j.util.exception.WebAuthnException;
import com.webauthn4j.verifier.exception.BadChallengeException;
import com.webauthn4j.verifier.exception.VerificationException;
import io.lettuce.core.RedisException;
import io.lettuce.core.api.async.RedisAsyncCommands;
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
@@ -88,6 +97,10 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
import org.whispersystems.textsecuregcm.auth.webauthn.RegistrationCeremonyParameters;
import org.whispersystems.textsecuregcm.auth.webauthn.RegistrationCeremonyResult;
import org.whispersystems.textsecuregcm.auth.webauthn.WebAuthnCeremonyManager;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
@@ -148,6 +161,7 @@ class AccountsManagerTest {
private RedisAdvancedClusterAsyncCommands<String, String> asyncClusterCommands;
private AccountsManager accountsManager;
private SecureValueRecoveryClient svr2Client;
private WebAuthnCeremonyManager webAuthnCeremonyManager;
private static final Answer<?> ACCOUNT_UPDATE_ANSWER = (answer) -> {
// it is implicit in the update() contract is that a successful call will
@@ -236,6 +250,8 @@ class AccountsManagerTest {
when(disconnectionRequestManager.requestDisconnection(any())).thenReturn(CompletableFuture.completedFuture(null));
webAuthnCeremonyManager = mock(WebAuthnCeremonyManager.class);
accountsManager = new AccountsManager(
accounts,
phoneNumberIdentifiers,
@@ -254,7 +270,8 @@ class AccountsManagerTest {
mock(ScheduledExecutorService.class),
CLOCK,
LINK_DEVICE_SECRET,
MAX_TOTP_VALIDATION_DELAY);
MAX_TOTP_VALIDATION_DELAY,
webAuthnCeremonyManager);
}
@ParameterizedTest
@@ -2205,4 +2222,376 @@ class AccountsManagerTest {
return Instant.ofEpochMilli((instant.toEpochMilli() / AccountsManager.TOTP.getTimeStep().toMillis()) *
AccountsManager.TOTP.getTimeStep().toMillis());
}
@Nested
class WebAuthn {
/// Creates an [AnnotatedWebAuthnCredential] with the given `credentialId` and a sign counter of 1
private static AnnotatedWebAuthnCredential createWebAuthnCredential(byte[] credentialId) {
return new AnnotatedWebAuthnCredential(
new AttestedCredentialData(
AAGUID.ZERO,
credentialId,
TestDataUtil.createEC2COSEPublicKey()),
1,
TestRandomUtil.nextBytes(160));
}
private static AnnotatedTotpKey createTotpKey() {
return new AnnotatedTotpKey(new TotpKey(TOTP_PARAMETERS, TestRandomUtil.nextBytes(16)),
TestRandomUtil.nextBytes(16));
}
private Account retrievableAccount(final Map<Byte, AnnotatedMfaKey> mfaKeys, final boolean hasPhoneNumber) {
final Account account = new Account();
account.setAccountIdentifier(UUID.randomUUID());
if (hasPhoneNumber) {
final String number = PhoneNumberUtil.getInstance().format(PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
account.setNumber(number, UUID.randomUUID());
}
account.setMfaKeys(mfaKeys);
addRetrievableAccount(account);
doAnswer(ACCOUNT_UPDATE_ANSWER).when(accounts).update(any());
return account;
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void startWebAuthnRegistration(final boolean hasPhoneNumber) throws TooManyMfaKeysException {
final AnnotatedWebAuthnCredential existingCredential = createWebAuthnCredential(TestRandomUtil.nextBytes(16));
final Account account = retrievableAccount(Map.of(
(byte) 1, existingCredential,
(byte) 2, createTotpKey()),
hasPhoneNumber);
final RegistrationCeremonyParameters expectedParameters =
new RegistrationCeremonyParameters(TestRandomUtil.nextBytes(32), List.of(-7L), List.of());
when(webAuthnCeremonyManager.startRegistration(any(), any())).thenReturn(expectedParameters);
assertEquals(expectedParameters, accountsManager.startWebAuthnRegistration(account.getAccountIdentifier()));
verify(webAuthnCeremonyManager).startRegistration(account.getAccountIdentifier(), List.of(existingCredential));
}
@CartesianTest
void startWebAuthnRegistrationTooManyMfaKeys(
@CartesianTest.Values(booleans = {true, false}) final boolean hasPhoneNumber,
@CartesianTest.Values(ints = {0, AccountsManager.MAX_MFA_KEYS - 1, AccountsManager.MAX_MFA_KEYS}) final int currentMfaKeyCount) {
final Account account = retrievableAccount(IntStream.range(0, currentMfaKeyCount)
.boxed()
.collect(Collectors.toMap(Integer::byteValue, _ -> createWebAuthnCredential(TestRandomUtil.nextBytes(16)))),
hasPhoneNumber);
when(webAuthnCeremonyManager.startRegistration(any(), any())).thenReturn(
new RegistrationCeremonyParameters(TestRandomUtil.nextBytes(32),
List.of(COSEAlgorithmIdentifier.ES256.getValue()), List.of()));
if (currentMfaKeyCount >= AccountsManager.MAX_MFA_KEYS) {
assertThrows(TooManyMfaKeysException.class,
() -> accountsManager.startWebAuthnRegistration(account.getAccountIdentifier()));
verifyNoInteractions(webAuthnCeremonyManager);
} else {
assertDoesNotThrow(() -> accountsManager.startWebAuthnRegistration(account.getAccountIdentifier()));
}
}
@Test
void startWebAuthnRegistrationAccountNotFound() {
final UUID accountIdentifier = UUID.randomUUID();
when(accounts.getByAccountIdentifier(accountIdentifier)).thenReturn(Optional.empty());
assertThrows(AccountNotFoundException.class,
() -> accountsManager.startWebAuthnRegistration(accountIdentifier));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void finishWebAuthnRegistration(final boolean hasPhoneNumber) throws TooManyMfaKeysException {
final Account account = retrievableAccount(Map.of((byte) 0, createTotpKey()), hasPhoneNumber);
final AnnotatedWebAuthnCredential newCredential = createWebAuthnCredential(TestRandomUtil.nextBytes(16));
final byte[] metadataCiphertext = newCredential.metadataCiphertext();
when(webAuthnCeremonyManager.verifyRegistration(any(), any())).thenReturn(
new RegistrationCeremonyResult(
newCredential.getAttestedCredentialData(), newCredential.getClientData(), 7));
final Optional<Byte> maybeKeyId = accountsManager.finishWebAuthnRegistration(
account.getAccountIdentifier(), TestRandomUtil.nextBytes(64), "{}", metadataCiphertext);
assertEquals(Optional.of((byte) 1), maybeKeyId);
final AnnotatedMfaKey storedKey = account.getMfaKeys().get((byte) 1);
assertInstanceOf(AnnotatedWebAuthnCredential.class, storedKey);
assertEquals(7, ((AnnotatedWebAuthnCredential) storedKey).getCounter());
assertArrayEquals(metadataCiphertext, storedKey.metadataCiphertext());
assertInstanceOf(AnnotatedTotpKey.class, account.getMfaKeys().get((byte) 0), "pre-existing TOTP key is unaffected");
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void finishWebAuthnRegistrationAlreadyRegistered(final boolean hasPhoneNumber) throws TooManyMfaKeysException {
final AnnotatedWebAuthnCredential existingCredential = createWebAuthnCredential(TestRandomUtil.nextBytes(16));
final byte existingKeyId = (byte) 3;
final Account account = retrievableAccount(Map.of(existingKeyId, existingCredential), hasPhoneNumber);
when(webAuthnCeremonyManager.verifyRegistration(any(), any())).thenReturn(
new RegistrationCeremonyResult(
existingCredential.getAttestedCredentialData(), existingCredential.getClientData(), 0));
final Optional<Byte> maybeKeyId = accountsManager.finishWebAuthnRegistration(
account.getAccountIdentifier(), TestRandomUtil.nextBytes(64), "{}", TestRandomUtil.nextBytes(160));
// Re-registering the same credential returns the existing key ID and leaves the stored credential untouched
assertEquals(Optional.of(existingKeyId), maybeKeyId);
assertEquals(Map.of(existingKeyId, existingCredential), account.getMfaKeys());
verify(accounts, never()).update(any());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void finishWebAuthnRegistrationVerificationFailed(final boolean hasPhoneNumber) throws TooManyMfaKeysException {
final Account account = retrievableAccount(Map.of(), hasPhoneNumber);
when(webAuthnCeremonyManager.verifyRegistration(any(), any())).thenThrow(new WebAuthnException("bad registration"));
assertTrue(accountsManager.finishWebAuthnRegistration(
account.getAccountIdentifier(), TestRandomUtil.nextBytes(64), "{}", TestRandomUtil.nextBytes(160))
.isEmpty());
assertEquals(Map.of(), account.getMfaKeys());
verify(accounts, never()).update(any());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void finishWebAuthnRegistrationTooManyMfaKeys(final boolean hasPhoneNumber) {
// The setup is a little confusing, but the scenario is:
// - client calls startWebAuthnRegistration() more than MAX_MFA_KEYS times (there's no stored state to prevent this)
// - client proceeds to verifyRegistration() with each of them
final Account account = retrievableAccount(IntStream.range(0, AccountsManager.MAX_MFA_KEYS)
.boxed()
.collect(Collectors.toMap(Integer::byteValue, _ -> createWebAuthnCredential(TestRandomUtil.nextBytes(16)))),
hasPhoneNumber);
final AnnotatedWebAuthnCredential newCredential = createWebAuthnCredential(TestRandomUtil.nextBytes(16));
when(webAuthnCeremonyManager.verifyRegistration(any(), any())).thenReturn(
new RegistrationCeremonyResult(
newCredential.getAttestedCredentialData(), newCredential.getClientData(), 0));
assertThrows(TooManyMfaKeysException.class, () -> accountsManager.finishWebAuthnRegistration(
account.getAccountIdentifier(), TestRandomUtil.nextBytes(64), "{}", TestRandomUtil.nextBytes(160)));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void startWebAuthnAuthentication(final boolean hasPhoneNumber) {
final AnnotatedWebAuthnCredential credential = createWebAuthnCredential(TestRandomUtil.nextBytes(16));
final Account account = retrievableAccount(Map.of((byte) 1, credential, (byte) 2, createTotpKey()), hasPhoneNumber);
final AuthenticationCeremonyParameters expectedParameters =
new AuthenticationCeremonyParameters(
TestRandomUtil.nextBytes(16), Duration.ofMinutes(2), List.of(credential.getCredentialId()));
when(webAuthnCeremonyManager.startAuthentication(any(), any())).thenReturn(expectedParameters);
assertEquals(Optional.of(expectedParameters), accountsManager.startWebAuthnAuthentication(account));
verify(webAuthnCeremonyManager).startAuthentication(account.getAccountIdentifier(), List.of(credential));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void startWebAuthnAuthenticationNoWebAuthnCredentials(final boolean hasPhoneNumber) {
final Account account = retrievableAccount(Map.of((byte) 1, createTotpKey()), hasPhoneNumber);
assertEquals(Optional.empty(), accountsManager.startWebAuthnAuthentication(account));
verifyNoInteractions(webAuthnCeremonyManager);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void verifyWebAuthnAuthentication(final boolean hasPhoneNumber) throws VerificationException {
final Account account;
final AnnotatedWebAuthnCredential credential;
final AuthenticationData authenticationData;
final byte webAuthnKeyId = (byte) 1;
final byte totpKeyId = (byte) 2;
{
final AnnotatedWebAuthnCredential storedCredential = createWebAuthnCredential(TestRandomUtil.nextBytes(16));
final AnnotatedTotpKey totpKey = createTotpKey();
final Account storedAccount = retrievableAccount(
Map.of(webAuthnKeyId, storedCredential, totpKeyId, totpKey),
hasPhoneNumber);
// The account the caller uses and the account re-read from storage inside update() are distinct objects
// deserialized separately, so they hold distinct (but equal) credential instances to start
account = new Account();
account.setAccountIdentifier(storedAccount.getAccountIdentifier());
if (hasPhoneNumber) {
account.setNumber("+18005550123", storedAccount.getPhoneNumberIdentifier().orElseThrow());
}
credential = new AnnotatedWebAuthnCredential(
storedCredential.getAttestedCredentialData(),
storedCredential.getCounter(),
storedCredential.metadataCiphertext().clone());
account.setMfaKeys(
Map.of(webAuthnKeyId, credential,
totpKeyId, new AnnotatedTotpKey(totpKey.totpKey(),
totpKey.metadataCiphertext().clone())));
authenticationData = mock(AuthenticationData.class);
when(authenticationData.getCredentialId()).thenReturn(storedCredential.getCredentialId());
}
when(webAuthnCeremonyManager.parseAuthenticationResponse(any())).thenReturn(authenticationData);
// webauthn4j updates the credential record's counter in place while verifying
doAnswer(invocation -> {
invocation.getArgument(1, AnnotatedWebAuthnCredential.class).setCounter(42);
return null;
}).when(webAuthnCeremonyManager).verifyAuthentication(any(), any(), any());
assertTrue(accountsManager.verifyWebAuthnAuthentication(account, "{}").isPresent());
verify(webAuthnCeremonyManager).verifyAuthentication(account.getAccountIdentifier(), credential, authenticationData);
// The account object from the caller has its counter updated, since it gets used by the mock
assertEquals(42, ((AnnotatedWebAuthnCredential) account.getMfaKeys().get(webAuthnKeyId)).getCounter());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void verifyWebAuthnAuthenticationUnrecognizedCredentialId(final boolean hasPhoneNumber) {
final Account account = retrievableAccount(Map.of((byte) 1, createWebAuthnCredential(TestRandomUtil.nextBytes(16))),
hasPhoneNumber);
final AuthenticationData authenticationData = mock(AuthenticationData.class);
when(authenticationData.getCredentialId()).thenReturn(TestRandomUtil.nextBytes(32));
when(webAuthnCeremonyManager.parseAuthenticationResponse(any())).thenReturn(authenticationData);
assertFalse(accountsManager.verifyWebAuthnAuthentication(account, "{}").isPresent());
verify(accounts, never()).update(any());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void verifyWebAuthnAuthenticationNoWebAuthnCredentials(final boolean hasPhoneNumber) {
final Account account = retrievableAccount(Map.of((byte) 1, createTotpKey()), hasPhoneNumber);
final AuthenticationData authenticationData = mock(AuthenticationData.class);
when(authenticationData.getCredentialId()).thenReturn(TestRandomUtil.nextBytes(32));
when(webAuthnCeremonyManager.parseAuthenticationResponse(any())).thenReturn(authenticationData);
assertFalse(accountsManager.verifyWebAuthnAuthentication(account, "{}").isPresent());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void verifyWebAuthnAuthenticationMalformedResponse(final boolean hasPhoneNumber) {
final Account account = retrievableAccount(Map.of((byte) 1, createWebAuthnCredential(TestRandomUtil.nextBytes(16))),
hasPhoneNumber);
when(webAuthnCeremonyManager.parseAuthenticationResponse(any())).thenThrow(new WebAuthnException("malformed"));
assertFalse(accountsManager.verifyWebAuthnAuthentication(account, "not json").isPresent());
verify(accounts, never()).update(any());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void verifyWebAuthnAuthenticationVerificationFailed(final boolean hasPhoneNumber) throws VerificationException {
final AnnotatedWebAuthnCredential credential = createWebAuthnCredential(TestRandomUtil.nextBytes(16));
final Account account = retrievableAccount(Map.of((byte) 1, credential), hasPhoneNumber);
final AuthenticationData authenticationData = mock(AuthenticationData.class);
when(authenticationData.getCredentialId()).thenReturn(credential.getCredentialId());
when(webAuthnCeremonyManager.parseAuthenticationResponse(any())).thenReturn(authenticationData);
doThrow(new BadChallengeException("expired")).when(webAuthnCeremonyManager).verifyAuthentication(any(), any(), any());
assertFalse(accountsManager.verifyWebAuthnAuthentication(account, "{}").isPresent());
verify(accounts, never()).update(any());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void verifyWebAuthnAuthenticationCounterChangedConcurrently(final boolean hasPhoneNumber)
throws VerificationException {
final AnnotatedWebAuthnCredential credential = createWebAuthnCredential(TestRandomUtil.nextBytes(16));
final Account account = retrievableAccount(Map.of((byte) 1, credential), hasPhoneNumber);
final AuthenticationData authenticationData = mock(AuthenticationData.class);
when(authenticationData.getCredentialId()).thenReturn(credential.getCredentialId());
when(webAuthnCeremonyManager.parseAuthenticationResponse(any())).thenReturn(authenticationData);
// Simulate a concurrent verification
final Account concurrentlyUpdatedAccount = new Account();
concurrentlyUpdatedAccount.setAccountIdentifier(account.getAccountIdentifier());
if (hasPhoneNumber) {
concurrentlyUpdatedAccount.setNumber(account.getNumber().orElseThrow(), UUID.randomUUID());
}
concurrentlyUpdatedAccount.setMfaKeys(Map.of((byte) 1,
new AnnotatedWebAuthnCredential(credential.getAttestedCredentialData(),
credential.getCounter() + 7, credential.metadataCiphertext())));
addRetrievableAccount(concurrentlyUpdatedAccount);
assertFalse(accountsManager.verifyWebAuthnAuthentication(account, "{}").isPresent());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void verifyWebAuthnAuthenticationKeyIdChangedConcurrently(final boolean hasPhoneNumber)
throws VerificationException {
final AnnotatedWebAuthnCredential credential = createWebAuthnCredential(TestRandomUtil.nextBytes(16));
final Account account = retrievableAccount(Map.of((byte) 1, credential), hasPhoneNumber);
final AuthenticationData authenticationData = mock(AuthenticationData.class);
when(authenticationData.getCredentialId()).thenReturn(credential.getCredentialId());
when(webAuthnCeremonyManager.parseAuthenticationResponse(any())).thenReturn(authenticationData);
// Simulate a concurrent verification
final Account concurrentlyUpdatedAccount = new Account();
concurrentlyUpdatedAccount.setAccountIdentifier(account.getAccountIdentifier());
if (hasPhoneNumber) {
concurrentlyUpdatedAccount.setNumber(account.getNumber().orElseThrow(), UUID.randomUUID());
}
// This credential was concurrently inserted. It (somehow) took the original credential’s key ID and has the same counter
// value
final AnnotatedWebAuthnCredential verySimilarInsertedCredential = createWebAuthnCredential(TestRandomUtil.nextBytes(16));
concurrentlyUpdatedAccount.setMfaKeys(Map.of((byte) 1,
new AnnotatedWebAuthnCredential(verySimilarInsertedCredential.getAttestedCredentialData(), credential.getCounter(),
verySimilarInsertedCredential.metadataCiphertext()),
(byte) 2, new AnnotatedWebAuthnCredential(credential.getAttestedCredentialData(),
credential.getCounter(), credential.metadataCiphertext())));
addRetrievableAccount(concurrentlyUpdatedAccount);
assertFalse(accountsManager.verifyWebAuthnAuthentication(account, "{}").isPresent());
}
}
}
@@ -157,7 +157,8 @@ class AccountsManagerUsernameIntegrationTest {
Executors.newSingleThreadScheduledExecutor(),
Clock.systemUTC(),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2));
AccountsManager.TOTP.getTimeStep().dividedBy(2),
null);
}
@Test
@@ -27,6 +27,9 @@ import com.eatthepath.otp.HmacOneTimePasswordGenerator;
import com.eatthepath.otp.TimeBasedOneTimePasswordGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.webauthn4j.data.attestation.authenticator.AAGUID;
import com.webauthn4j.data.attestation.authenticator.AttestedCredentialData;
import com.webauthn4j.test.TestDataUtil;
import jakarta.annotation.Nullable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -629,6 +632,37 @@ class AccountsTest {
assertThat(reclaimed.getMfaKeys()).isEqualTo(existingAccount.getMfaKeys());
}
@Test
void testMfaKeysRoundTrip() {
final UUID existingUuid = UUID.randomUUID();
final byte[] accountRecoveryPassword = TestRandomUtil.nextBytes(16);
final Account existingAccount = generateAccount("+14151112222", existingUuid, UUID.randomUUID(),
List.of(generateDevice(DEVICE_ID_1)), accountRecoveryPassword);
final AnnotatedWebAuthnCredential webAuthnCredential = new AnnotatedWebAuthnCredential(
new AttestedCredentialData(AAGUID.ZERO, TestRandomUtil.nextBytes(32), TestDataUtil.createEC2COSEPublicKey()),
42,
TestRandomUtil.nextBytes(160));
final AnnotatedTotpKey totpKey = new AnnotatedTotpKey(new TotpKey(
new TotpParameters(
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA1,
HmacOneTimePasswordGenerator.DEFAULT_PASSWORD_LENGTH,
TimeBasedOneTimePasswordGenerator.DEFAULT_TIME_STEP),
TestRandomUtil.nextBytes(16)),
TestRandomUtil.nextBytes(16));
final Map<Byte, AnnotatedMfaKey> mfaKeys = Map.of((byte) 1, webAuthnCredential, (byte) 2, totpKey);
existingAccount.setMfaKeys(mfaKeys);
createAccount(existingAccount);
final Account retrieved = accounts.getByAccountIdentifier(existingUuid).orElseThrow();
assertThat(retrieved.getMfaKeys()).isEqualTo(mfaKeys);
}
@ParameterizedTest
@ValueSource(strings = {"+14151112222"})
@NullSource
@@ -156,7 +156,8 @@ public class AddRemoveDeviceIntegrationTest {
scheduledExecutorService,
clock,
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2));
AccountsManager.TOTP.getTimeStep().dividedBy(2),
null);
accountsManager.start();
}
@@ -0,0 +1,69 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.params.provider.Arguments.argumentSet;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.webauthn4j.test.TestDataUtil;
import java.util.Collection;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class AnnotatedWebAuthnCredentialTest {
private static AnnotatedWebAuthnCredential credential(final long counter, final byte[] metadataCiphertext) {
return new AnnotatedWebAuthnCredential(
TestDataUtil.createAttestedCredentialData(),
counter,
metadataCiphertext);
}
@Test
void testEquals() {
final AnnotatedWebAuthnCredential credential = credential(2, TestRandomUtil.nextBytes(160));
final AnnotatedWebAuthnCredential sameCredential = new AnnotatedWebAuthnCredential(
credential.getAttestedCredentialData(),
credential.getCounter(),
credential.metadataCiphertext().clone());
assertEquals(credential, sameCredential);
}
@ParameterizedTest
@MethodSource
void serializationRoundTrips(final JsonRoundTrip roundTrip) throws JsonProcessingException {
final AnnotatedWebAuthnCredential credential = credential(1, TestRandomUtil.nextBytes(160));
assertEquals(credential, roundTrip.apply(credential));
}
static Collection<Arguments> serializationRoundTrips() {
return List.of(
argumentSet("AnnotatedWebAuthnCredential", (JsonRoundTrip) credential ->
SystemMapper.jsonMapper().readValue(
SystemMapper.jsonMapper().writeValueAsString(credential), AnnotatedWebAuthnCredential.class)),
argumentSet("AnnotatedMfaKey JsonSubType", (JsonRoundTrip) credential ->
SystemMapper.jsonMapper().readValue(
SystemMapper.jsonMapper().writeValueAsString((AnnotatedMfaKey) credential), AnnotatedMfaKey.class))
);
}
@FunctionalInterface
private interface JsonRoundTrip {
AnnotatedMfaKey apply(AnnotatedWebAuthnCredential credential) throws JsonProcessingException;
}
}
@@ -178,3 +178,5 @@ hlrLookup.apiKey: AAAAAAAAAAA
hlrLookup.apiSecret: AAAAAAAAAAA
foundationDbMessages.versionstampCipherKey.0: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
registrationWebAuthn.userHandleBlindingSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
@@ -577,3 +577,9 @@ foundationDbMessages:
epochs:
0:
- messages-0
registrationWebAuthn:
relyingPartyId: example.org
origin: https://example.org
challengeTtl: PT2M
userHandleBlindingSecret: secret://registrationWebAuthn.userHandleBlindingSecret