Compare commits

...
Author SHA1 Message Date
Jon Chambers 79757458d6 Introduce an experiment to use FoundationDB as the primary source for "live" messages 2026-09-16 10:46:35 -04:00
Jon Chambers c09aab080f Rename the "answer challenge" method and normalize "not permitted" responses 2026-09-16 10:27:38 -04:00
Jon Chambers 580960d958 Add a gRPC endpoint for requesting push challenges 2026-09-16 10:27:38 -04:00
Ravi Khadiwala c21475e3e7 Add an 'impossible' marker to mismatched number logs 2026-09-16 10:17:52 -04:00
Jon Chambers 09b5289d83 Add a gRPC endpoint for reporting spam 2026-09-16 10:16:40 -04:00
Jon Chambers f66bd0858d Introduce ReportMessageHelper 2026-09-16 10:16:40 -04:00
Jon Chambers ce8cc80f66 Retire unused "report spam via e164" pathway 2026-09-16 10:16:40 -04:00
Chris Eager 66b5412103 Update netty to 4.2.18 2026-09-16 10:06:13 -04:00
Chris Eager 11b6894dae Add backend tag to H2FrameProxyHandler writability changed metric 2026-09-16 10:05:55 -04:00
moiseev-signal 02b86d67ad Override domain in KT gRPC errors with chat domain 2026-09-16 09:56:41 -04:00
Jon Chambers f55c3c22fe Clarify naming and reduce duplication in CredentialsGrpcService 2026-09-16 09:20:48 -04:00
Jonathan Klabunde Tomer eb601cd51e Add WebAuthn MFA key support 2026-09-14 10:48:37 -04:00
Jon Chambers 2ee739dbe1 Add a dynamic configuration flag to fail open in the event of upstream captcha errors 2026-09-14 10:35:04 -04:00
Jon Chambers a15b70476d Add a gauge for concurrent FoundationDB transactions 2026-09-14 10:34:58 -04:00
Ameya Lokare 5f124cc812 Port /v1/archives/backupid/limits to gRPC 2026-09-14 10:34:51 -04:00
Chris Eager ce3378354d Address various deprecations 2026-09-14 10:30:24 -04:00
Ravi Khadiwala cb02200a24 Delete updated user at end of testRecoverWithTotp 2026-09-11 16:55:41 -04:00
90 changed files with 3873 additions and 576 deletions

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;
@@ -74,11 +96,12 @@ public class AccountTest {
public void testRecoverWithTotp()
throws VerificationFailedException, InvalidInputException, NoSuchAlgorithmException, InvalidKeyException {
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
final TestUser originalUser = Operations.registerNumberlessUser(receipt.credential());
TestUser user = Operations.registerNumberlessUser(receipt.credential());
final UUID originalAci = user.aciUuid();
try {
final GenerateTotpKeyResponse generateTotpKeyResponse =
getAccountsStubForUser(originalUser).generateTotpKey(GenerateTotpKeyRequest.getDefaultInstance());
getAccountsStubForUser(user).generateTotpKey(GenerateTotpKeyRequest.getDefaultInstance());
assertEquals(GenerateTotpKeyResponse.ResponseCase.KEY_GENERATED, generateTotpKeyResponse.getResponseCase());
final TotpParameters totpParameters = generateTotpKeyResponse.getKeyGenerated().getTotpParameters();
@@ -93,7 +116,7 @@ public class AccountTest {
final byte[] totpMetadata = Operations.randomBytes(160);
final ConfirmTotpKeyResponse confirmTotpKeyResponse = getAccountsStubForUser(originalUser)
final ConfirmTotpKeyResponse confirmTotpKeyResponse = getAccountsStubForUser(user)
.confirmTotpKey(ConfirmTotpKeyRequest.newBuilder()
.setOneTimePassword(totpGenerator.generateOneTimePassword(totpKey, Instant.now()))
.setMetadataCiphertext(ByteString.copyFrom(totpMetadata))
@@ -101,14 +124,13 @@ public class AccountTest {
assertEquals(ConfirmTotpKeyResponse.ResponseCase.KEY_CONFIRMED, confirmTotpKeyResponse.getResponseCase());
final int keyId = confirmTotpKeyResponse.getKeyConfirmed().getKeyId();
final TestUser recoveredUser =
Operations.recoverNumberlessUser(originalUser, totpGenerator.generateOneTimePassword(totpKey, Instant.now()));
user = Operations.recoverNumberlessUserWithTotp(user, totpGenerator.generateOneTimePassword(totpKey, Instant.now()));
assertEquals(originalUser.aciUuid(), recoveredUser.aciUuid());
assertEquals(user.aciUuid(), originalAci);
// MFA key should remain set after re-registration
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> mfaKeys =
getAccountsStubForUser(recoveredUser).listMfaKeys(ListMfaKeysRequest.getDefaultInstance()).getKeysMap();
getAccountsStubForUser(user).listMfaKeys(ListMfaKeysRequest.getDefaultInstance()).getKeysMap();
assertEquals(1, mfaKeys.size());
assertTrue(mfaKeys.containsKey(keyId));
@@ -117,7 +139,70 @@ public class AccountTest {
} finally {
Operations.deleteReceipt(receipt.serial());
Operations.deleteUser(originalUser);
Operations.deleteUser(user);
}
}
@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);
}
}
+2 -1
View File
@@ -77,7 +77,7 @@
<log4j-bom.version>2.26.1</log4j-bom.version>
<luajava.version>4.1.0</luajava.version>
<micrometer.version>1.17.1</micrometer.version>
<netty.version>4.2.17.Final</netty.version>
<netty.version>4.2.18.Final</netty.version>
<!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
<!-- the latest 4.x should be fine https://central.sonatype.com/artifact/com.google.protobuf/protobuf-java/versions -->
<protobuf.version>4.36.0</protobuf.version>
@@ -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());
@@ -1068,7 +1077,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final HttpClient shortCodeRetrieverHttpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10)).build();
final ShortCodeExpander shortCodeRetriever = new ShortCodeExpander(shortCodeRetrieverHttpClient, config.getShortCodeRetrieverConfiguration().baseUrl());
final CaptchaChecker captchaChecker = new CaptchaChecker(shortCodeRetriever, captchaClientSupplier);
final CaptchaChecker captchaChecker = new CaptchaChecker(shortCodeRetriever, captchaClientSupplier, dynamicConfigurationManager);
final RegistrationCaptchaManager registrationCaptchaManager = new RegistrationCaptchaManager(captchaChecker);
@@ -1123,7 +1132,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, asnInfoProviderSupplier, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
new MessagesGrpcService(accountsManager, reportMessageManager, phoneNumberIdentifiers, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters, gcsAttachmentGenerator,
@@ -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);
}
}
@@ -9,7 +9,6 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import jakarta.ws.rs.BadRequestException;
import java.io.IOException;
import java.util.Locale;
import java.util.Optional;
@@ -19,6 +18,8 @@ import java.util.function.Function;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
public class CaptchaChecker {
private static final Logger logger = LoggerFactory.getLogger(CaptchaChecker.class);
@@ -33,12 +34,15 @@ public class CaptchaChecker {
private final ShortCodeExpander shortCodeExpander;
private final Function<String, CaptchaClient> captchaClientSupplier;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
public CaptchaChecker(
final ShortCodeExpander shortCodeRetriever,
final Function<String, CaptchaClient> captchaClientSupplier) {
final Function<String, CaptchaClient> captchaClientSupplier,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.shortCodeExpander = shortCodeRetriever;
this.captchaClientSupplier = captchaClientSupplier;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
@@ -105,12 +109,21 @@ public class CaptchaChecker {
throw new InvalidCaptchaArgumentException("invalid captcha site-key");
}
final AssessmentResult result = client.verify(maybeAci, siteKey, parsedAction, token, ip, userAgent);
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
"action", action,
"score", result.getScoreString(),
"provider", provider)
.increment();
return result;
try {
final AssessmentResult result = client.verify(maybeAci, siteKey, parsedAction, token, ip, userAgent);
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
"action", action,
"score", result.getScoreString(),
"provider", provider)
.increment();
return result;
} catch (final IOException | RuntimeException e) {
if (dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration().isFailOpen()) {
logger.warn("Failed to verify captcha; failing open", e);
return AssessmentResult.alwaysValid();
}
throw e;
}
}
}
@@ -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) {
}
@@ -35,6 +35,9 @@ public class DynamicCaptchaConfiguration {
@NotNull
private Map<Action, BigDecimal> scoreFloorByAction = Collections.emptyMap();
@JsonProperty
private boolean failOpen = false;
public BigDecimal getScoreFloor() {
return scoreFloor;
}
@@ -66,4 +69,11 @@ public class DynamicCaptchaConfiguration {
this.hCaptchaSiteKeys = hCaptchaSiteKeys;
}
public boolean isFailOpen() {
return failOpen;
}
public void setFailOpen(final boolean failOpen) {
this.failOpen = failOpen;
}
}
@@ -91,9 +91,9 @@ import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ReportMessageHelper;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Util;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v1/messages")
@@ -605,7 +605,7 @@ public class MessageController {
CompletableFuture.allOf(resolvedRecipients.values()
.stream()
.map(account -> account.getAccountIdentifier())
.map(Account::getAccountIdentifier)
.map(accountIdentifier ->
rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture())
.toList()
@@ -731,45 +731,10 @@ public class MessageController {
@Path("/report/{source}/{messageGuid}")
public Response reportSpamMessage(
@Auth AuthenticatedDevice auth,
@PathParam("source") String source,
@PathParam("source") UUID source,
@PathParam("messageGuid") UUID messageGuid,
@Nullable SpamReport spamReport,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent
) {
final Optional<String> sourceNumber;
final Optional<UUID> sourceAci;
final Optional<UUID> sourcePni;
boolean sourceAccountDeleted = false;
if (source.startsWith("+")) {
sourceNumber = Optional.of(source);
final Optional<Account> maybeAccount = accountsManager.getByE164(source);
if (maybeAccount.isPresent()) {
sourceAci = maybeAccount.map(Account::getAccountIdentifier);
sourcePni = maybeAccount.flatMap(Account::getPhoneNumberIdentifier);
} else {
sourcePni = Optional.ofNullable(phoneNumberIdentifiers.getPhoneNumberIdentifier(source).join());
sourceAci = sourcePni.flatMap(accountsManager::findRecentlyDeletedAccountIdentifier);
sourceAccountDeleted = true;
}
} else {
sourceAci = Optional.of(UUID.fromString(source));
final Optional<Account> sourceAccount = accountsManager.getByAccountIdentifier(sourceAci.get());
if (sourceAccount.isEmpty()) {
logger.warn("Could not find source: {}", sourceAci.get());
sourcePni = accountsManager.findRecentlyDeletedPhoneNumberIdentifier(sourceAci.get());
sourceNumber = sourcePni.flatMap(pni ->
Util.getCanonicalNumber(phoneNumberIdentifiers.getPhoneNumber(pni).join()));
sourceAccountDeleted = true;
} else {
sourceNumber = sourceAccount.flatMap(Account::getNumber);
sourcePni = sourceAccount.flatMap(Account::getPhoneNumberIdentifier);
}
}
final UUID spamReporterUuid = auth.accountIdentifier();
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent) {
// spam report token is optional, but if provided ensure it is non-empty.
final Optional<byte[]> maybeSpamReportToken =
@@ -777,7 +742,14 @@ public class MessageController {
.flatMap(r -> Optional.ofNullable(r.token()))
.filter(t -> t.length > 0);
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid, maybeSpamReportToken, userAgent, sourceAccountDeleted);
ReportMessageHelper.reportMessage(new AciServiceIdentifier(source),
new AciServiceIdentifier(auth.accountIdentifier()),
messageGuid,
maybeSpamReportToken.orElse(null),
userAgent,
accountsManager,
phoneNumberIdentifiers,
reportMessageManager);
return Response.status(Status.ACCEPTED)
.build();
@@ -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()
@@ -16,6 +16,7 @@ import java.util.Optional;
import java.util.stream.Collectors;
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
import org.signal.chat.backup.GetBackupAuthCredentialsResponse;
import org.signal.chat.backup.GetBackupIdLimitsResponse;
import org.signal.chat.backup.RedeemReceiptRequest;
import org.signal.chat.backup.RedeemReceiptResponse;
import org.signal.chat.backup.SetBackupIdRequest;
@@ -138,6 +139,16 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
}
}
@Override
public GetBackupIdLimitsResponse getBackupIdLimits(final Empty request) {
final Account account = authenticatedAccount();
final BackupAuthManager.BackupIdRotationLimit limit = backupAuthManager.checkBackupIdRotationLimit(account);
return GetBackupIdLimitsResponse.newBuilder()
.setHasPermitsRemaining(limit.hasPermitsRemaining())
.setRetryAfterSeconds(limit.nextPermitAvailable().getSeconds())
.build();
}
@Override
public Throwable mapException(final Throwable throwable) {
return switch (throwable) {
@@ -1,14 +1,18 @@
package org.whispersystems.textsecuregcm.grpc;
import java.io.IOException;
import com.google.protobuf.Empty;
import org.signal.chat.challenge.AnswerChallengeRequest;
import org.signal.chat.challenge.AnswerChallengeResponse;
import org.signal.chat.challenge.RequestPushChallengeRequest;
import org.signal.chat.challenge.RequestPushChallengeResponse;
import org.signal.chat.challenge.SimpleChallengeGrpc;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.signal.chat.errors.FailedPrecondition;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.captcha.InvalidCaptchaArgumentException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -28,19 +32,21 @@ public class ChallengeGrpcService extends SimpleChallengeGrpc.ChallengeImplBase
}
@Override
public AnswerChallengeResponse handleChallengeResponse(final AnswerChallengeRequest request)
public AnswerChallengeResponse answerChallenge(final AnswerChallengeRequest request)
throws RateLimitExceededException, IOException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
final ChallengeConstraintChecker.ChallengeConstraints constraints = challengeConstraintChecker.challengeConstraintsGrpc(
account);
final Account account = requireAuthenticatedAccount();
final ChallengeConstraintChecker.ChallengeConstraints constraints =
challengeConstraintChecker.challengeConstraintsGrpc(account);
final boolean success = switch (request.getRequestCase()) {
case PUSH -> constraints.pushPermitted() && rateLimitChallengeManager.answerPushChallenge(account,
request.getPush().getChallenge());
case PUSH -> {
if (!constraints.pushPermitted()) {
throw GrpcExceptions.rateLimitExceeded(null);
}
yield rateLimitChallengeManager.answerPushChallenge(account, request.getPush().getChallenge());
}
case CAPTCHA -> {
try {
yield rateLimitChallengeManager.answerCaptchaChallenge(
@@ -49,7 +55,7 @@ public class ChallengeGrpcService extends SimpleChallengeGrpc.ChallengeImplBase
RequestAttributesUtil.getRemoteAddress().getHostAddress(),
RequestAttributesUtil.getUserAgent().orElse(null),
constraints.captchaScoreThreshold());
} catch (InvalidCaptchaArgumentException e) {
} catch (final InvalidCaptchaArgumentException e) {
throw GrpcExceptions.invalidArguments(e.getMessage());
}
}
@@ -60,4 +66,32 @@ public class ChallengeGrpcService extends SimpleChallengeGrpc.ChallengeImplBase
.setSuccess(success)
.build();
}
@Override
public RequestPushChallengeResponse requestPushChallenge(final RequestPushChallengeRequest request) {
final Account account = requireAuthenticatedAccount();
final ChallengeConstraintChecker.ChallengeConstraints constraints =
challengeConstraintChecker.challengeConstraintsGrpc(account);
if (!constraints.pushPermitted()) {
throw GrpcExceptions.rateLimitExceeded(null);
}
try {
rateLimitChallengeManager.sendPushChallenge(account);
} catch (NotPushRegisteredException _) {
return RequestPushChallengeResponse.newBuilder()
.setNoPushToken(FailedPrecondition.getDefaultInstance())
.build();
}
return RequestPushChallengeResponse.newBuilder()
.setSentPushChallenge(Empty.getDefaultInstance())
.build();
}
private Account requireAuthenticatedAccount() {
return accountsManager.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
}
}
@@ -12,9 +12,10 @@ import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.signal.chat.common.ZkCredential;
import org.signal.chat.credentials.ExternalServiceType;
import org.signal.chat.credentials.GetCreateCallLinkCredentialsRequest;
import org.signal.chat.credentials.GetCreateCallLinkCredentialsResponse;
import org.signal.chat.credentials.GetCreateCallLinkCredentialRequest;
import org.signal.chat.credentials.GetCreateCallLinkCredentialResponse;
import org.signal.chat.credentials.GetDeliveryCertificateRequest;
import org.signal.chat.credentials.GetDeliveryCertificateResponse;
import org.signal.chat.credentials.GetExternalServiceCredentialsRequest;
@@ -138,14 +139,14 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
.orElseThrow(
() -> new IllegalStateException("account without PNI must have auth credential salt")),
redemption));
responseBuilder.addGroupCredentials(GetGroupCredentialsResponse.CredentialAndRedemptionTime.newBuilder()
.setRedemptionTimeSeconds(redemption.getEpochSecond())
responseBuilder.addGroupCredentials(ZkCredential.newBuilder()
.setRedemptionTime(redemption.getEpochSecond())
.setCredential(ByteString.copyFrom(
authCredentialWithPniResponse.serialize()))
.build());
responseBuilder.addCallLinkAuthCredentials(GetGroupCredentialsResponse.CredentialAndRedemptionTime.newBuilder()
.setRedemptionTimeSeconds(redemption.getEpochSecond())
responseBuilder.addCallLinkAuthCredentials(ZkCredential.newBuilder()
.setRedemptionTime(redemption.getEpochSecond())
.setCredential(ByteString.copyFrom(
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, serverSecretParams).serialize()))
.build());
@@ -155,7 +156,7 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
}
@Override
public GetCreateCallLinkCredentialsResponse getCreateCallLinkCredentials(final GetCreateCallLinkCredentialsRequest request)
public GetCreateCallLinkCredentialResponse getCreateCallLinkCredential(final GetCreateCallLinkCredentialRequest request)
throws RateLimitExceededException {
final UUID accountIdentifier = AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier();
@@ -167,8 +168,7 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
final CreateCallLinkCredentialRequest createCallLinkCredentialRequest =
new CreateCallLinkCredentialRequest(request.getCredentialRequest().toByteArray());
return GetCreateCallLinkCredentialsResponse.newBuilder()
.setRedemptionTimeSeconds(truncatedDayTimestamp.getEpochSecond())
return GetCreateCallLinkCredentialResponse.newBuilder()
.setCredential(ByteString.copyFrom(createCallLinkCredentialRequest.issueCredential(
new ServiceId.Aci(accountIdentifier),
truncatedDayTimestamp,
@@ -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();
@@ -0,0 +1,26 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.rpc.ErrorInfo;
import java.io.UncheckedIOException;
import java.util.Optional;
public class ErrorUtil {
public static Optional<ErrorInfo> errorInfo(final com.google.rpc.Status statusProto) {
return statusProto.getDetailsList().stream()
.filter(any -> any.is(ErrorInfo.class))
.map(errorInfo -> {
try {
return errorInfo.unpack(ErrorInfo.class);
} catch (final InvalidProtocolBufferException e) {
throw new UncheckedIOException(e);
}
})
.findFirst();
}
}
@@ -6,22 +6,19 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.Status;
import org.signal.keytransparency.client.AciMonitorRequest;
import org.signal.keytransparency.client.ConsistencyParameters;
import com.google.protobuf.Any;
import com.google.rpc.ErrorInfo;
import com.google.rpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.protobuf.StatusProto;
import org.signal.keytransparency.client.DistinguishedRequest;
import org.signal.keytransparency.client.DistinguishedResponse;
import org.signal.keytransparency.client.E164MonitorRequest;
import org.signal.keytransparency.client.E164SearchRequest;
import org.signal.keytransparency.client.MonitorRequest;
import org.signal.keytransparency.client.MonitorResponse;
import org.signal.keytransparency.client.MonitorResponseV2;
import org.signal.keytransparency.client.SearchRequest;
import org.signal.keytransparency.client.SearchResponse;
import org.signal.keytransparency.client.SearchResponseV2;
import org.signal.keytransparency.client.SimpleKeyTransparencyQueryServiceGrpc;
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
@@ -88,4 +85,28 @@ public class KeyTransparencyGrpcService extends
return request;
}
@Override
public Throwable mapException(final Throwable throwable) {
// Reconstruct the exception so that we can override the backing service domain with chat's own domain.
if (throwable instanceof StatusRuntimeException s) {
final ErrorInfo.Builder errInfoBuilder = ErrorInfo.newBuilder()
.setDomain(GrpcExceptions.DOMAIN);
final Status statusProto = StatusProto.fromStatusAndTrailers(s.getStatus(), s.getTrailers());
ErrorUtil.errorInfo(statusProto)
.map(ErrorInfo::getReason)
.ifPresent(errInfoBuilder::setReason);
return StatusProto.toStatusRuntimeException(Status.newBuilder()
// See https://github.com/signalapp/key-transparency-server/blob/30b7a2a40604fbe04545d47f26e4c5a35f5d3161/cmd/kt-server/errors.go#L32
// for a list of error codes that the key transparency service can generate.
.setCode(statusProto.getCode())
.setMessage(statusProto.getMessage())
.addDetails(Any.pack(errInfoBuilder.build()))
.build());
}
return throwable;
}
}
@@ -20,6 +20,8 @@ import org.signal.chat.errors.NotFound;
import org.signal.chat.messages.GetMessagesRequest;
import org.signal.chat.messages.GetMessagesResponse;
import org.signal.chat.messages.IndividualRecipientMessageBundle;
import org.signal.chat.messages.ReportMessageRequest;
import org.signal.chat.messages.ReportMessageResponse;
import org.signal.chat.messages.SendAuthenticatedSenderMessageRequest;
import org.signal.chat.messages.SendMessageAuthenticatedSenderResponse;
import org.signal.chat.messages.SendMessageType;
@@ -44,6 +46,9 @@ import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ReportMessageHelper;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
@@ -52,6 +57,8 @@ import javax.annotation.Nullable;
public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
private final AccountsManager accountsManager;
private final ReportMessageManager reportMessageManager;
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private final RateLimiters rateLimiters;
private final MessageSender messageSender;
private final CardinalityEstimator messageByteLimitEstimator;
@@ -63,6 +70,8 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
SendMessageAuthenticatedSenderResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
public MessagesGrpcService(final AccountsManager accountsManager,
final ReportMessageManager reportMessageManager,
final PhoneNumberIdentifiers phoneNumberIdentifiers,
final RateLimiters rateLimiters,
final MessageSender messageSender,
final CardinalityEstimator messageByteLimitEstimator,
@@ -71,6 +80,8 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
final Clock clock) {
this.accountsManager = accountsManager;
this.reportMessageManager = reportMessageManager;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.rateLimiters = rateLimiters;
this.messageSender = messageSender;
this.messageByteLimitEstimator = messageByteLimitEstimator;
@@ -261,4 +272,22 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
throw GrpcExceptions.invalidArguments("unrecognized envelope type");
};
}
@Override
public ReportMessageResponse reportMessage(final ReportMessageRequest request) {
final ServiceIdentifier sourceServiceIdentifier =
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getSourceServiceIdentifier());
ReportMessageHelper.reportMessage(
sourceServiceIdentifier,
new AciServiceIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier()),
UUIDUtil.fromByteString(request.getMessageGuid()),
request.getReportSpamToken().isEmpty() ? null : request.getReportSpamToken().toByteArray(),
RequestAttributesUtil.getUserAgent().orElse(null),
accountsManager,
phoneNumberIdentifiers,
reportMessageManager);
return ReportMessageResponse.getDefaultInstance();
}
}
@@ -127,7 +127,7 @@ public class MetricServerInterceptor implements ServerInterceptor {
@Override
public void close(final Status status, final Metadata responseHeaders) {
if (!status.isOk()) {
reason = errorInfo(StatusProto.fromStatusAndTrailers(status, responseHeaders))
reason = ErrorUtil.errorInfo(StatusProto.fromStatusAndTrailers(status, responseHeaders))
.map(ErrorInfo::getReason)
.orElse(DEFAULT_ERROR_REASON);
}
@@ -232,16 +232,4 @@ public class MetricServerInterceptor implements ServerInterceptor {
}
}
private static Optional<ErrorInfo> errorInfo(final com.google.rpc.Status statusProto) {
return statusProto.getDetailsList().stream()
.filter(any -> any.is(ErrorInfo.class))
.map(errorInfo -> {
try {
return errorInfo.unpack(ErrorInfo.class);
} catch (final InvalidProtocolBufferException e) {
throw new UncheckedIOException(e);
}
})
.findFirst();
}
}
@@ -20,9 +20,11 @@ public class H2FrameProxyHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(H2FrameProxyHandler.class);
private static final String WRITABILITY_CHANGED_COUNTER_NAME = MetricsUtil.name(H2FrameProxyHandler.class, "writabilityChanged");
private static final String BACKEND_TAG_NAME = "backend";
private final Channel peerStream;
private final String proxyNameTag;
private final String backendNameTag;
// If we fail to write to the peerStream, we want to close the inbound channel. Rather than allocate a new listener
// that captures the inbound ChannelHandlerContext on every message, we capture the ChannelHandlerContext in
@@ -30,9 +32,10 @@ public class H2FrameProxyHandler extends ChannelInboundHandlerAdapter {
// one channel, but we already have a designated peerStream so this handler is fundamentally single-channel.
private ChannelFutureListener closeInboundOnPeerFailure = null;
public H2FrameProxyHandler(final Channel peerStream, final String proxyNameTag) {
public H2FrameProxyHandler(final Channel peerStream, final String proxyNameTag, final String backendNameTag) {
this.peerStream = peerStream;
this.proxyNameTag = proxyNameTag;
this.backendNameTag = backendNameTag;
}
@Override
@@ -50,8 +53,9 @@ public class H2FrameProxyHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelWritabilityChanged(final ChannelHandlerContext peerCtx) throws Exception {
Metrics.counter(WRITABILITY_CHANGED_COUNTER_NAME,
"isWritable", Boolean.toString(peerCtx.channel().isWritable()),
"proxy", proxyNameTag)
"isWritable", Boolean.toString(peerCtx.channel().isWritable()),
"proxy", proxyNameTag,
BACKEND_TAG_NAME, backendNameTag)
.increment();
ctx.channel().config().setAutoRead(peerStream.isWritable());
super.channelWritabilityChanged(peerCtx);
@@ -145,7 +145,7 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
// Connected, open a new H2 stream to the backend so we can proxy the client's frames
logger.trace("Opening a HTTP/2 stream to the backend {}", target);
final Channel backendConnection = connectFuture.channel();
createBackendProxyStream(ctx, backendConnection, headersFrame);
createBackendProxyStream(ctx, backendConnection, headersFrame, backendTag);
});
}
@@ -155,13 +155,15 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
/// @param backendConnection An established H2 connection [Channel], on which a new h2 stream will be opened
/// @param headersFrame The first `headersFrame` from the client h2 stream that should be forwarded to the new
/// backend stream
/// @param backendTag The backend this stream targets, for metrics
private void createBackendProxyStream(
final ChannelHandlerContext clientStreamCtx,
final Channel backendConnection,
final Http2HeadersFrame headersFrame) {
final Http2HeadersFrame headersFrame,
final String backendTag) {
new Http2StreamChannelBootstrap(backendConnection)
// Forwards response frames from the backend back to the client stream
.handler(new H2FrameProxyHandler(clientStreamCtx.channel(), "responseStream"))
.handler(new H2FrameProxyHandler(clientStreamCtx.channel(), "responseStream", backendTag))
.open()
.addListener((io.netty.util.concurrent.Future<Http2StreamChannel> streamFuture) -> {
if (!streamFuture.isSuccess()) {
@@ -194,7 +196,7 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
clientStreamCtx.pipeline().replace(
OmnibusH2StreamHandler.this,
"backend-to-client-proxy",
new H2FrameProxyHandler(backendStream, "requestStream"));
new H2FrameProxyHandler(backendStream, "requestStream", backendTag));
clientStreamCtx.channel().pipeline().fireChannelRead(headersFrame);
// Resume inbound reads, which should now be forwarded
@@ -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();
}
}
@@ -44,6 +44,7 @@ import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
import software.amazon.awssdk.core.SdkBytes;
@@ -1800,7 +1801,8 @@ public class Accounts {
final String attributeNumber = AttributeValues.getString(item, ATTR_ACCOUNT_E164, null);
if (!account.getNumber().equals(Optional.ofNullable(attributeNumber))) {
log.error("Mismatched phone numbers for account {}. From JSON: {}; from attribute: {}",
ImpossibleEvents.logImpossible(log,
"Mismatched phone numbers for account {}. From JSON: {}; from attribute: {}",
accountIdentifier, account.getNumber(), attributeNumber);
}
@@ -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()));
}
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
public class ConcatenatingMessageStream implements MessageStream {
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
private final FoundationDbMessageStream foundationDbMessageStream;
private static final Counter CONFLICTING_CONSUMER_COUNTER =
Metrics.counter(MetricsUtil.name(ConcatenatingMessageStream.class, "conflictingConsumer"));
public ConcatenatingMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
final FoundationDbMessageStream foundationDbMessageStream) {
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
this.foundationDbMessageStream = foundationDbMessageStream;
}
@Override
public Flow.Publisher<MessageStreamEntry> getMessages() {
return JdkFlowAdapter.publisherToFlowPublisher(Flux.concat(
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages()),
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages()))
.doOnError(throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof ConflictingMessageConsumerException) {
CONFLICTING_CONSUMER_COUNTER.increment();
}
}));
}
@Override
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
return CompletableFuture.allOf(
redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp),
messageGuid.version() == 8
? foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
: CompletableFuture.completedFuture(null));
}
}
@@ -73,6 +73,9 @@ public class MessagesManager {
@VisibleForTesting
static final String MIRROR_READS_EXPERIMENT_NAME = "foundationDbMirrorReads";
@VisibleForTesting
static final String READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME = "foundationDbReadLiveMessages";
private final MessagesDynamoDb messagesDynamoDb;
private final MessagesCache messagesCache;
private final FoundationDbMessageStore foundationDbMessageStore;
@@ -287,9 +290,17 @@ public class MessagesManager {
}
public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) {
if (experimentEnrollmentManager.isEnrolled(destinationUuid, READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME)) {
return new ConcatenatingMessageStream(
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
destinationUuid, destinationDevice, true),
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId())
);
}
final RedisDynamoDbMessageStream redisDynamoDbMessageStream =
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
destinationUuid, destinationDevice);
destinationUuid, destinationDevice, false);
return new MirroringMessageStream(
redisDynamoDbMessageStream,
@@ -20,9 +20,9 @@ import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
/// A Redis/DynamoDB message publisher produces a non-terminating stream of messages for a specific device. It listens
/// for message availability signals from [RedisMessageAvailabilityManager] and emits new messages to its subscriber
/// when available.
/// A Redis/DynamoDB message publisher produces an optionally-terminating stream of messages for a specific device. It
/// listens for message availability signals from [RedisMessageAvailabilityManager] and emits new messages to its
/// subscriber when available.
///
/// This publisher supports only a single subscriber. It assumes that subscribers acknowledge (delete) messages as they
/// read the messages, and may emit duplicate messages if subscribers do not acknowledge messages before requesting more
@@ -36,6 +36,8 @@ class RedisDynamoDbMessagePublisher implements MessageAvailabilityListener, Flow
private final UUID accountIdentifier;
private final Device device;
private final boolean terminateOnQueueEmpty;
// Indicates which data source(s) we think might contain messages for the destination device. Messages initially land
// in Redis, but are eventually "persisted" to DynamoDB. This state changes in response to signals this publisher
// receives as a MessageAvailabilityListener. As an initial state, we assume that we have messages in both DynamoDB
@@ -133,13 +135,15 @@ class RedisDynamoDbMessagePublisher implements MessageAvailabilityListener, Flow
final MessagesCache messagesCache,
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
final UUID accountIdentifier,
final Device device) {
final Device device,
final boolean terminateOnQueueEmpty) {
this.messagesDynamoDb = messagesDynamoDb;
this.messagesCache = messagesCache;
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
this.accountIdentifier = accountIdentifier;
this.device = device;
this.terminateOnQueueEmpty = terminateOnQueueEmpty;
}
@Override
@@ -151,9 +155,12 @@ class RedisDynamoDbMessagePublisher implements MessageAvailabilityListener, Flow
this.subscriber = subscriber;
// Listen for signals indicating that new messages are available in Redis, that messages have been persisted from
// Redis to DynamoDB, or that there's a conflicting message reader connected somewhere else
redisMessageAvailabilityManager.handleClientConnected(accountIdentifier, device.getId(), this);
if (!terminateOnQueueEmpty) {
// If we're trying to follow a live stream of messages, then listen for signals indicating that new messages are
// available in Redis, that messages have been persisted from Redis to DynamoDB, or that there's a conflicting
// message reader connected somewhere else
redisMessageAvailabilityManager.handleClientConnected(accountIdentifier, device.getId(), this);
}
subscriber.onSubscribe(new Flow.Subscription() {
@Override
@@ -216,6 +223,11 @@ class RedisDynamoDbMessagePublisher implements MessageAvailabilityListener, Flow
return false;
}
// Don't send a "queue empty" signal if we're supposed to terminate when the queue is empty
if (terminateOnQueueEmpty) {
return false;
}
// The machinery that produces messages won't activate until we have a subscriber
assert subscriber != null;
@@ -249,6 +261,24 @@ class RedisDynamoDbMessagePublisher implements MessageAvailabilityListener, Flow
return;
}
if (acknowledgedEntries < publishedEntries) {
// To avoid double-reading messages from data stores that don't support cursors, don't get a new message source
// unless all previously-published signals have been acknowledged (when messages are acknowledged, we'll come back
// to this point with a higher value for `acknowledgedEntries` via `handleMessageAcknowledged`)
return;
}
if (terminateOnQueueEmpty && queueEmptySignalState == QueueEmptySignalState.PENDING) {
// If we've acknowledged everything we've published and we're ready to send a "queue empty" signal, we can use the
// "ready to send a 'queue empty' signal" state as our cue to terminate the subscription
assert subscriber != null;
subscriber.onComplete();
terminate();
return;
}
if (storedMessageState == StoredMessageState.EMPTY) {
// We don't think there are any messages in either message source; don't do anything until the situation changes
// (when new messages arrive, we'll come back to this point with a non-empty stored message state)
@@ -261,13 +291,6 @@ class RedisDynamoDbMessagePublisher implements MessageAvailabilityListener, Flow
return;
}
if (acknowledgedEntries < publishedEntries) {
// To avoid double-reading messages from data stores that don't support cursors, don't get a new message source
// unless all previously-published signals have been acknowledged (when messages are acknowledged, we'll come back
// to this point with a higher value for `acknowledgedEntries` via `handleMessageAcknowledged`)
return;
}
// We maybe be able to skip reading from DynamoDB entirely if we think messages are only stored in Redis
final Publisher<MessageProtos.Envelope> dynamoPublisher =
storedMessageState == StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE
@@ -9,7 +9,6 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
@@ -41,13 +40,15 @@ public class RedisDynamoDbMessageStream implements MessageStream {
final MessagesCache messagesCache,
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
final UUID accountIdentifier,
final Device device) {
final Device device,
final boolean terminateOnQueueEmpty) {
this(messagesDynamoDb, messagesCache, accountIdentifier, device, new RedisDynamoDbMessagePublisher(messagesDynamoDb,
messagesCache,
redisMessageAvailabilityManager,
accountIdentifier,
device));
device,
terminateOnQueueEmpty));
}
@VisibleForTesting
@@ -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);
}
}
@@ -0,0 +1,57 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.util.Optional;
import java.util.UUID;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.Util;
public class ReportMessageHelper {
private static final Logger logger = LoggerFactory.getLogger(ReportMessageHelper.class);
public static void reportMessage(final ServiceIdentifier sourceServiceIdentifier,
final AciServiceIdentifier reporterServiceIdentifier,
final UUID messageGuid,
@Nullable final byte[] reportSpamToken,
@Nullable final String userAgent,
final AccountsManager accountsManager,
final PhoneNumberIdentifiers phoneNumberIdentifiers,
final ReportMessageManager reportMessageManager) {
final Optional<String> maybeSourceNumber;
final Optional<UUID> maybeSourcePni;
final boolean sourceAccountDeleted;
final Optional<Account> sourceAccount = accountsManager.getByServiceIdentifier(sourceServiceIdentifier);
if (sourceAccount.isEmpty()) {
logger.warn("Could not find source: {}", sourceServiceIdentifier);
maybeSourcePni = accountsManager.findRecentlyDeletedPhoneNumberIdentifier(sourceServiceIdentifier.uuid());
maybeSourceNumber = maybeSourcePni.flatMap(pni ->
Util.getCanonicalNumber(phoneNumberIdentifiers.getPhoneNumber(pni).join()));
sourceAccountDeleted = true;
} else {
maybeSourceNumber = sourceAccount.flatMap(Account::getNumber);
maybeSourcePni = sourceAccount.flatMap(Account::getPhoneNumberIdentifier);
sourceAccountDeleted = false;
}
reportMessageManager.report(maybeSourceNumber,
sourceServiceIdentifier.uuid(),
maybeSourcePni,
messageGuid,
reporterServiceIdentifier.uuid(),
Optional.ofNullable(reportSpamToken),
userAgent,
sourceAccountDeleted);
}
}
@@ -23,6 +23,7 @@ import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import javax.annotation.Nullable;
public class ReportMessageManager {
@@ -61,17 +62,17 @@ public class ReportMessageManager {
}
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public void report(final Optional<String> sourceNumber,
final Optional<UUID> sourceAci,
final UUID sourceAci,
final Optional<UUID> sourcePni,
final UUID messageGuid,
final UUID reporterUuid,
final Optional<byte[]> reportSpamToken,
final String reporterUserAgent,
@Nullable final String reporterUserAgent,
final boolean sourceAccountDeleted) {
final boolean found = sourceAci.map(uuid -> reportMessageDynamoDb.remove(hash(messageGuid, uuid.toString())))
.orElse(false);
final boolean found = reportMessageDynamoDb.remove(hash(messageGuid, sourceAci.toString()));
Metrics.counter(REPORT_MESSAGE_COUNTER_NAME,
Tags.of(FOUND_MESSAGE_TAG, String.valueOf(found),
@@ -87,11 +88,11 @@ public class ReportMessageManager {
connection.sync().expire(reportedSenderKey, counterTtl.toSeconds());
});
sourceAci.ifPresent(aci -> {
final String reportedSenderKey = getReportedSenderAciKey(aci);
{
final String reportedSenderKey = getReportedSenderAciKey(sourceAci);
connection.sync().pfadd(reportedSenderKey, reporterUuid.toString());
connection.sync().expire(reportedSenderKey, counterTtl.toSeconds());
});
}
});
reportedMessageListeners.forEach(listener -> {
@@ -11,8 +11,10 @@ import com.apple.foundationdb.ReadTransaction;
import com.apple.foundationdb.Transaction;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import jakarta.annotation.Nullable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Function;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
@@ -23,18 +25,24 @@ public class FaultTolerantDatabase {
private final Database database;
private final CircuitBreaker circuitBreaker;
private final LongAdder concurrentTransactionCount;
public FaultTolerantDatabase(
final Database database,
final String circuitBreakerName,
final String name,
@Nullable final String circuitBreakerConfigurationName) {
this.database = database;
this.circuitBreaker = circuitBreakerConfigurationName != null
? ResilienceUtil.getCircuitBreakerRegistry().circuitBreaker(circuitBreakerName, circuitBreakerConfigurationName)
: ResilienceUtil.getCircuitBreakerRegistry().circuitBreaker(circuitBreakerName);
? ResilienceUtil.getCircuitBreakerRegistry().circuitBreaker(name, circuitBreakerConfigurationName)
: ResilienceUtil.getCircuitBreakerRegistry().circuitBreaker(name);
this.concurrentTransactionCount =
Metrics.gauge(MetricsUtil.name(getClass(), "concurrentTransactions"), Tags.of("name", name), new LongAdder());
}
public <T> T run(final Function<? super Transaction, T> retryable, final Context context) {
try {
concurrentTransactionCount.increment();
return circuitBreaker.executeSupplier(() -> database.run(retryable));
} catch (final Exception e) {
if (e instanceof final FDBException fdbException) {
@@ -44,6 +52,8 @@ public class FaultTolerantDatabase {
).increment();
}
throw e;
} finally {
concurrentTransactionCount.decrement();
}
}
@@ -57,7 +67,10 @@ public class FaultTolerantDatabase {
/// @return a cancellation-safe version of the future returned from [Database#runAsync(Function)]
public <T> CompletableFuture<T> runAsync(final Function<? super Transaction, ? extends CompletableFuture<T>> retryable,
final Context context) {
return circuitBreaker.executeCompletionStage(() -> database.runAsync(retryable)
concurrentTransactionCount.increment();
final CompletableFuture<T> runAsyncFuture = circuitBreaker.executeCompletionStage(() -> database.runAsync(retryable)
.whenComplete((_, throwable) -> {
if (throwable != null && ExceptionUtils.unwrap(throwable) instanceof final FDBException fdbException) {
Metrics.counter(TRANSACTION_ERRORS_COUNTER,
@@ -68,10 +81,15 @@ public class FaultTolerantDatabase {
})
.thenApply(Function.identity()))
.toCompletableFuture();
runAsyncFuture.whenComplete((_, _) -> concurrentTransactionCount.decrement());
return runAsyncFuture;
}
public <T> T read(final Function<? super ReadTransaction, T> retryable, final Context context) {
try {
concurrentTransactionCount.increment();
return circuitBreaker.executeSupplier(() -> database.read(retryable));
} catch (final Exception e) {
if (e instanceof final FDBException fdbException) {
@@ -81,13 +99,18 @@ public class FaultTolerantDatabase {
).increment();
}
throw e;
} finally {
concurrentTransactionCount.decrement();
}
}
public <T> CompletableFuture<T> readAsync(
final Function<? super ReadTransaction, ? extends CompletableFuture<T>> retryable,
final Context context) {
return circuitBreaker.executeCompletionStage(() -> database.readAsync(retryable)
concurrentTransactionCount.increment();
final CompletableFuture<T> readAsyncFuture = circuitBreaker.executeCompletionStage(() -> database.readAsync(retryable)
.whenComplete((_, throwable) -> {
if (throwable != null && ExceptionUtils.unwrap(throwable) instanceof final FDBException fdbException) {
Metrics.counter(TRANSACTION_ERRORS_COUNTER,
@@ -97,6 +120,10 @@ public class FaultTolerantDatabase {
}
}))
.toCompletableFuture();
readAsyncFuture.whenComplete((_, _) -> concurrentTransactionCount.decrement());
return readAsyncFuture;
}
public enum Context {
@@ -25,13 +25,12 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.LongAdder;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StaticException;
import org.eclipse.jetty.util.ConstantThrowable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
@@ -329,6 +328,6 @@ public class WebSocketConnection {
return throwable instanceof java.nio.channels.ClosedChannelException ||
throwable == WebSocketResourceProvider.CONNECTION_CLOSED_EXCEPTION ||
throwable instanceof org.eclipse.jetty.io.EofException ||
(throwable instanceof StaticException staticException && "Closed".equals(staticException.getMessage()));
(throwable instanceof ConstantThrowable constantThrowable && "Closed".equals(constantThrowable.getMessage()));
}
}
@@ -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"];
@@ -59,6 +59,9 @@ service Backups {
// Clients must validate the receipt level on the credential matches a known
// receipt level before using it.
rpc GetBackupAuthCredentials(GetBackupAuthCredentialsRequest) returns (GetBackupAuthCredentialsResponse) {}
// Retrieve backup ID rotation limits
rpc GetBackupIdLimits(google.protobuf.Empty) returns (GetBackupIdLimitsResponse) {}
}
message SetBackupIdRequest {
@@ -125,6 +128,13 @@ message GetBackupAuthCredentialsResponse {
Credentials credentials = 1;
}
message GetBackupIdLimitsResponse {
// If true, a call to SetBackupId may succeed without waiting
bool hasPermitsRemaining = 1;
// How long to wait before a permit becomes available, in seconds
uint64 retryAfterSeconds = 2;
}
// Service for backup operations with anonymous credentials
//
// This service never requires account authentication. It instead requires a
@@ -9,17 +9,46 @@ option java_multiple_files = true;
package org.signal.chat.challenge;
import "google/protobuf/empty.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/require.proto";
import "org/signal/chat/tag.proto";
service Challenge {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
// Submit proof of a challenge completion
// Some server endpoints (the "send message" endpoint, for example) may return
// a response indicating the client must complete a challenge before continuing.
// Clients may use this endpoint to provide proof of a completed challenge.
// If successful, the client may then continue their original operation.
rpc HandleChallengeResponse(AnswerChallengeRequest) returns (AnswerChallengeResponse) {}
// Submit proof of a challenge completion.
//
// Some server endpoints (the "send message" endpoint, for example) may return
// a response indicating the client must complete a challenge before continuing.
// Clients may use this endpoint to provide proof of a completed challenge.
// If successful, the client may then continue their original operation.
rpc AnswerChallenge(AnswerChallengeRequest) returns (AnswerChallengeResponse) {}
// Requests that a challenge value be sent to the authenticated account's
// primary device via push notification. Once received, callers may present
// the challenge value via the HandleChallengeResponse RPC.
//
// APNs challenge payloads will be formatted as follows:
//
// ```
// {
// "aps": {
// "sound": "default",
// "alert": {
// "loc-key": "APN_Message"
// }
// },
// "rateLimitChallenge": "{CHALLENGE_TOKEN}"
// }
// ```
//
// FCM challenge payloads will be formatted as follows:
//
// ```
// {"rateLimitChallenge": "{CHALLENGE_TOKEN}"}
// ```
rpc RequestPushChallenge(RequestPushChallengeRequest) returns (RequestPushChallengeResponse) {}
}
message AnswerChallengeRequest {
@@ -43,10 +72,26 @@ message AnswerChallengeRequest {
AnswerPushChallengeRequest push = 2;
AnswerCaptchaChallengeRequest captcha = 3;
}
}
message AnswerChallengeResponse {
// Whether the challenge proof was accepted
bool success = 1;
}
message RequestPushChallengeRequest {
}
message RequestPushChallengeResponse {
message SentPushChallenge {
}
oneof response {
// The server attempted to send a challenge value to the authenticated
// account's primary device via a push notification.
google.protobuf.Empty sent_push_challenge = 1;
// The authenticated account's primary device does not have a push token.
errors.FailedPrecondition no_push_token = 2 [(tag.reason) = "no_push_token"];
}
}
@@ -7,6 +7,7 @@ syntax = "proto3";
option java_multiple_files = true;
import "org/signal/chat/common.proto";
import "org/signal/chat/require.proto";
package org.signal.chat.credentials;
@@ -33,8 +34,8 @@ service Credentials {
returns (GetGroupCredentialsResponse) {}
// Generates zero-knowledge credentials for creating call links.
rpc GetCreateCallLinkCredentials(GetCreateCallLinkCredentialsRequest)
returns (GetCreateCallLinkCredentialsResponse) {}
rpc GetCreateCallLinkCredential(GetCreateCallLinkCredentialRequest)
returns (GetCreateCallLinkCredentialResponse) {}
}
// Provides methods for working with previously-generated credentials without
@@ -130,37 +131,26 @@ message GetGroupCredentialsRequest {
}
message GetGroupCredentialsResponse {
// A zero-knowledge credential that may be redeemed at or up to one day after
// the given redemption time
message CredentialAndRedemptionTime {
bytes credential = 1;
uint64 redemption_time_seconds = 2;
}
// A collection of credentials allowing the holder to anonymously
// authenticate themselves for group-related actions
repeated CredentialAndRedemptionTime group_credentials = 1;
repeated common.ZkCredential group_credentials = 1;
// A collection of credentials allowing the holder to read, update, and delete
// group call links
repeated CredentialAndRedemptionTime call_link_auth_credentials = 2;
repeated common.ZkCredential call_link_auth_credentials = 2;
// The phone number identifier for which the included credentials were
// generated. Empty if the account does not have a phone number.
bytes pni = 3;
}
message GetCreateCallLinkCredentialsRequest {
message GetCreateCallLinkCredentialRequest {
// A zero-knowledge credential request
bytes credential_request = 1;
}
message GetCreateCallLinkCredentialsResponse {
message GetCreateCallLinkCredentialResponse {
// A zero-knowledge credential that may be redeemed at or up to one day after
// the given redemption time
bytes credential = 1;
// The earliest time, in seconds since the epoch, at which the associated
// credential may be redeemed
uint64 redemption_time_seconds = 2;
}
@@ -49,6 +49,9 @@ service Messages {
// a STREAM_CLOSED error reason. A GetMessagesStreamClosed message will be
// present in the error details.
rpc GetMessages(stream GetMessagesRequest) returns (stream GetMessagesResponse) {}
// Reports a message as spam.
rpc ReportMessage(ReportMessageRequest) returns (ReportMessageResponse) {}
}
message GetMessagesRequest {
@@ -435,3 +438,18 @@ message ChallengeRequired {
// resolved by waiting.
optional uint64 retry_after_seconds = 3;
}
message ReportMessageRequest {
// The service identifier of the party that sent the offending message
common.ServiceIdentifier source_service_identifier = 1;
// The GUID of the offending message
bytes message_guid = 2 [(require.exactlySize) = 16];
// The spam-reporting token attached to the offending message
bytes report_spam_token = 3;
}
message ReportMessageResponse {
}
@@ -130,10 +130,9 @@ public class ProvisioningTimeoutIntegrationTest {
when(testApplication.scheduler.schedule(any(Runnable.class), anyLong(), any()))
.thenReturn(mock(ScheduledFuture.class));
final ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest();
try (Session ignored = client.connect(testWebsocketListener,
URI.create(String.format("ws://127.0.0.1:%d/websocket", DROPWIZARD_APP_EXTENSION.getLocalPort())),
upgradeRequest).join()) {
final ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest(
URI.create(String.format("ws://127.0.0.1:%d/websocket", DROPWIZARD_APP_EXTENSION.getLocalPort())));
try (Session ignored = client.connect(testWebsocketListener, upgradeRequest).join()) {
assertThat(testWebsocketListener.provisioningAddressFuture.join()).isNotNull();
assertThat(testWebsocketListener.closeFuture()).isNotDone();
@@ -156,10 +155,9 @@ public class ProvisioningTimeoutIntegrationTest {
@SuppressWarnings("unchecked") final ScheduledFuture<Void> scheduled = mock(ScheduledFuture.class);
doReturn(scheduled).when(testApplication.scheduler).schedule(any(Runnable.class), anyLong(), any());
final ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest();
final Session session = client.connect(testWebsocketListener,
URI.create(String.format("ws://127.0.0.1:%d/websocket", DROPWIZARD_APP_EXTENSION.getLocalPort())),
upgradeRequest).join();
final ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest(
URI.create(String.format("ws://127.0.0.1:%d/websocket", DROPWIZARD_APP_EXTENSION.getLocalPort())));
final Session session = client.connect(testWebsocketListener, upgradeRequest).join();
// Close the websocket, make sure the timeout is cancelled.
session.close();
@@ -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);
}
}
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.captcha;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
@@ -15,7 +16,6 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.captcha.CaptchaChecker.SEPARATOR;
import jakarta.ws.rs.BadRequestException;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
@@ -23,9 +23,14 @@ import java.util.Optional;
import java.util.UUID;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
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.configuration.dynamic.DynamicCaptchaConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
public class CaptchaCheckerTest {
@@ -72,6 +77,19 @@ public class CaptchaCheckerTest {
return captchaClient;
}
private static DynamicConfigurationManager<DynamicConfiguration> mockDynamicConfigurationManager(final boolean failOpen) {
final DynamicCaptchaConfiguration dynamicCaptchaConfiguration = mock(DynamicCaptchaConfiguration.class);
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
mock(DynamicConfigurationManager.class);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
when(dynamicConfiguration.getCaptchaConfiguration()).thenReturn(dynamicCaptchaConfiguration);
when(dynamicCaptchaConfiguration.isFailOpen()).thenReturn(failOpen);
return dynamicConfigurationManager;
}
@ParameterizedTest
@MethodSource
@@ -81,7 +99,7 @@ public class CaptchaCheckerTest {
final String siteKey,
final Action expectedAction) throws IOException, InvalidCaptchaArgumentException {
final CaptchaClient captchaClient = mockClient(PREFIX);
new CaptchaChecker(null, PREFIX -> captchaClient).verify(Optional.empty(), expectedAction, input, null, USER_AGENT);
new CaptchaChecker(null, _ -> captchaClient, mockDynamicConfigurationManager(false)).verify(Optional.empty(), expectedAction, input, null, USER_AGENT);
verify(captchaClient, times(1)).verify(any(), eq(siteKey), eq(expectedAction), eq(expectedToken), any(), eq(USER_AGENT));
}
@@ -110,10 +128,10 @@ public class CaptchaCheckerTest {
final CaptchaClient b = mockClient(PREFIX_B);
final Map<String, CaptchaClient> captchaClientMap = Map.of(PREFIX_A, a, PREFIX_B, b);
new CaptchaChecker(null, captchaClientMap::get).verify(Optional.of(ACI), Action.CHALLENGE, ainput, null, USER_AGENT);
new CaptchaChecker(null, captchaClientMap::get, mockDynamicConfigurationManager(false)).verify(Optional.of(ACI), Action.CHALLENGE, ainput, null, USER_AGENT);
verify(a, times(1)).verify(any(), any(), any(), any(), any(), any());
new CaptchaChecker(null, captchaClientMap::get).verify(Optional.of(ACI), Action.CHALLENGE, binput, null, USER_AGENT);
new CaptchaChecker(null, captchaClientMap::get, mockDynamicConfigurationManager(false)).verify(Optional.of(ACI), Action.CHALLENGE, binput, null, USER_AGENT);
verify(b, times(1)).verify(any(), any(), any(), any(), any(), any());
}
@@ -135,7 +153,7 @@ public class CaptchaCheckerTest {
public void badArgs(final String input) throws IOException {
final CaptchaClient cc = mockClient(PREFIX);
assertThrows(InvalidCaptchaArgumentException.class,
() -> new CaptchaChecker(null, prefix -> PREFIX.equals(prefix) ? cc : null).verify(Optional.of(ACI), Action.CHALLENGE, input, null, USER_AGENT));
() -> new CaptchaChecker(null, prefix -> PREFIX.equals(prefix) ? cc : null, mockDynamicConfigurationManager(false)).verify(Optional.of(ACI), Action.CHALLENGE, input, null, USER_AGENT));
}
@@ -145,8 +163,28 @@ public class CaptchaCheckerTest {
final ShortCodeExpander retriever = mock(ShortCodeExpander.class);
when(retriever.retrieve("abc")).thenReturn(Optional.of(TOKEN));
final String input = String.join(SEPARATOR, PREFIX + "-short", REG_SITE_KEY, "registration", "abc");
new CaptchaChecker(retriever, ignored -> captchaClient).verify(Optional.of(ACI), Action.REGISTRATION, input, null, USER_AGENT);
new CaptchaChecker(retriever, _ -> captchaClient, mockDynamicConfigurationManager(false)).verify(Optional.of(ACI), Action.REGISTRATION, input, null, USER_AGENT);
verify(captchaClient, times(1)).verify(any(), eq(REG_SITE_KEY), eq(Action.REGISTRATION), eq(TOKEN), any(), any());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
public void failOpen(final boolean failOpen) throws IOException {
final CaptchaClient captchaClient = mockClient(PREFIX);
final String input = String.join(SEPARATOR, PREFIX, CHALLENGE_SITE_KEY, "challenge", TOKEN);
final Exception exception = new IOException();
when(captchaClient.verify(any(), any(), any(), any(), any(), any())).thenThrow(exception);
final Executable executable =
() -> new CaptchaChecker(null, _ -> captchaClient, mockDynamicConfigurationManager(failOpen)).verify(Optional.of(ACI), Action.CHALLENGE, input, null, USER_AGENT);
if (failOpen) {
assertDoesNotThrow(executable);
} else {
assertThrows(exception.getClass(), executable);
}
}
}
@@ -712,70 +712,6 @@ class MessageControllerTest {
}
}
@Test
void testReportMessageByE164() {
final String senderNumber = "+12125550001";
final UUID senderAci = UUID.randomUUID();
final UUID senderPni = UUID.randomUUID();
final String userAgent = "user-agent";
final UUID messageGuid = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getAccountIdentifier()).thenReturn(senderAci);
when(account.getNumber()).thenReturn(Optional.of(senderNumber));
when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(senderPni));
when(accountsManager.getByE164(senderNumber)).thenReturn(Optional.of(account));
try (final Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/report/%s/%s", senderNumber, messageGuid))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.header(HttpHeaders.USER_AGENT, userAgent)
.post(null)) {
assertThat(response.getStatus(), is(equalTo(202)));
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
messageGuid, AuthHelper.VALID_UUID, Optional.empty(), userAgent, false);
verify(accountsManager, never()).findRecentlyDeletedPhoneNumberIdentifier(any(UUID.class));
verify(phoneNumberIdentifiers, never()).getPhoneNumber(any());
}
}
@Test
void testReportMessageByE164DeletedAccount() {
final String senderNumber = "+12125550001";
final UUID senderAci = UUID.randomUUID();
final UUID senderPni = UUID.randomUUID();
final String userAgent = "user-agent";
final UUID messageGuid = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getAccountIdentifier()).thenReturn(senderAci);
when(account.getNumber()).thenReturn(Optional.of(senderNumber));
when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(senderPni));
when(accountsManager.getByE164(senderNumber)).thenReturn(Optional.empty());
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(senderNumber)).thenReturn(CompletableFuture.completedFuture(senderPni));
when(accountsManager.findRecentlyDeletedAccountIdentifier(senderPni)).thenReturn(Optional.of(senderAci));
try (final Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/report/%s/%s", senderNumber, messageGuid))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.header(HttpHeaders.USER_AGENT, userAgent)
.post(null)) {
assertThat(response.getStatus(), is(equalTo(202)));
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
messageGuid, AuthHelper.VALID_UUID, Optional.empty(), userAgent, true);
}
}
@Test
void testReportMessageByAci() {
final String senderNumber = "+12125550001";
@@ -789,7 +725,7 @@ class MessageControllerTest {
when(account.getNumber()).thenReturn(Optional.of(senderNumber));
when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(senderPni));
when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.of(account));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(senderAci))).thenReturn(Optional.of(account));
when(phoneNumberIdentifiers.getPhoneNumber(senderPni)).thenReturn(CompletableFuture.completedFuture(List.of(senderNumber)));
try (final Response response =
@@ -802,7 +738,7 @@ class MessageControllerTest {
assertThat(response.getStatus(), is(equalTo(202)));
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
verify(reportMessageManager).report(Optional.of(senderNumber), senderAci, Optional.of(senderPni),
messageGuid, AuthHelper.VALID_UUID, Optional.empty(), userAgent, false);
verify(accountsManager, never()).findRecentlyDeletedPhoneNumberIdentifier(any(UUID.class));
verify(phoneNumberIdentifiers, never()).getPhoneNumber(any());
@@ -836,7 +772,7 @@ class MessageControllerTest {
assertThat(response.getStatus(), is(equalTo(202)));
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
verify(reportMessageManager).report(Optional.of(senderNumber), senderAci, Optional.of(senderPni),
messageGuid, AuthHelper.VALID_UUID, Optional.empty(), userAgent, true);
}
}
@@ -854,7 +790,7 @@ class MessageControllerTest {
when(account.getNumber()).thenReturn(Optional.of(senderNumber));
when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(senderPni));
when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.of(account));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(senderAci))).thenReturn(Optional.of(account));
when(accountsManager.findRecentlyDeletedPhoneNumberIdentifier(senderAci)).thenReturn(Optional.of(senderPni));
when(phoneNumberIdentifiers.getPhoneNumber(senderPni)).thenReturn(CompletableFuture.completedFuture(List.of(senderNumber)));
@@ -869,7 +805,7 @@ class MessageControllerTest {
assertThat(response.getStatus(), is(equalTo(202)));
verify(reportMessageManager).report(eq(Optional.of(senderNumber)),
eq(Optional.of(senderAci)),
eq(senderAci),
eq(Optional.of(senderPni)),
eq(messageGuid),
eq(AuthHelper.VALID_UUID),
@@ -880,11 +816,13 @@ class MessageControllerTest {
verify(phoneNumberIdentifiers, never()).getPhoneNumber(any());
}
when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.empty());
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(senderAci))).thenReturn(Optional.empty());
messageGuid = UUID.randomUUID();
entity = Entity.entity(new SpamReport(new byte[5]), "application/json");
final byte[] reportSpamToken = new byte[5];
entity = Entity.entity(new SpamReport(reportSpamToken), "application/json");
try (final Response response =
resources.getJerseyTest()
@@ -895,11 +833,11 @@ class MessageControllerTest {
assertThat(response.getStatus(), is(equalTo(202)));
verify(reportMessageManager).report(eq(Optional.of(senderNumber)),
eq(Optional.of(senderAci)),
eq(senderAci),
eq(Optional.of(senderPni)),
eq(messageGuid),
eq(AuthHelper.VALID_UUID),
argThat(maybeBytes -> maybeBytes.map(bytes -> Arrays.equals(bytes, new byte[5])).orElse(false)),
argThat(maybeBytes -> maybeBytes.map(bytes -> Arrays.equals(bytes, reportSpamToken)).orElse(false)),
any(),
eq(true));
}
@@ -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));
}
}
@@ -14,6 +14,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import io.grpc.Status;
import java.time.Clock;
import java.time.Duration;
@@ -35,6 +36,7 @@ import org.mockito.Mock;
import org.signal.chat.backup.BackupsGrpc;
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
import org.signal.chat.backup.GetBackupAuthCredentialsResponse;
import org.signal.chat.backup.GetBackupIdLimitsResponse;
import org.signal.chat.backup.RedeemReceiptRequest;
import org.signal.chat.backup.RedeemReceiptResponse;
import org.signal.chat.backup.SetBackupIdRequest;
@@ -263,4 +265,22 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
() -> authenticatedServiceStub().getBackupAuthCredentials(builder.build()));
}
@ParameterizedTest
@CsvSource({
"true, 0",
"false, 3600"
})
void getBackupIdLimits(final boolean hasPermitsRemaining, final long retryAfterSeconds) {
when(backupAuthManager.checkBackupIdRotationLimit(account))
.thenReturn(new BackupAuthManager.BackupIdRotationLimit(
hasPermitsRemaining, Duration.ofSeconds(retryAfterSeconds)));
final GetBackupIdLimitsResponse response =
authenticatedServiceStub().getBackupIdLimits(Empty.getDefaultInstance());
assertThat(response.getHasPermitsRemaining()).isEqualTo(hasPermitsRemaining);
assertThat(response.getRetryAfterSeconds()).isEqualTo(retryAfterSeconds);
verify(backupAuthManager).checkBackupIdRotationLimit(account);
}
}
@@ -1,25 +1,31 @@
package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.time.Duration;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.junitpioneer.jupiter.cartesian.CartesianTest.Values;
import org.mockito.Mock;
import org.signal.chat.challenge.AnswerChallengeRequest;
import org.signal.chat.challenge.AnswerChallengeResponse;
import org.signal.chat.challenge.ChallengeGrpc;
import org.signal.chat.challenge.RequestPushChallengeRequest;
import org.signal.chat.challenge.RequestPushChallengeResponse;
import org.whispersystems.textsecuregcm.captcha.InvalidCaptchaArgumentException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -50,21 +56,42 @@ public class ChallengeGrpcServiceTest extends
);
}
@CartesianTest
void handlePushChallengeResponse(
@Values(booleans = {true, false}) final boolean pushPermitted,
@Values(booleans = {true, false}) final boolean success) throws RateLimitExceededException {
when(challengeConstraintChecker.challengeConstraintsGrpc(account)).thenReturn(
new ChallengeConstraintChecker.ChallengeConstraints(pushPermitted, Optional.empty()));
@ParameterizedTest
@ValueSource(booleans = {true, false})
void handlePushChallengeResponse(final boolean success) throws RateLimitExceededException {
when(challengeConstraintChecker.challengeConstraintsGrpc(account))
.thenReturn(new ChallengeConstraintChecker.ChallengeConstraints(true, Optional.empty()));
when(rateLimitChallengeManager.answerPushChallenge(account, "foo")).thenReturn(success);
final AnswerChallengeResponse response = authenticatedServiceStub().handleChallengeResponse(
final AnswerChallengeResponse response = authenticatedServiceStub().answerChallenge(
AnswerChallengeRequest.newBuilder()
.setToken("token")
.setPush(AnswerChallengeRequest.AnswerPushChallengeRequest.newBuilder()
.setChallenge("foo")
.build())
.build());
assertEquals(pushPermitted && success, response.getSuccess());
assertEquals(success, response.getSuccess());
}
@Test
void handlePushChallengeResponseNotPermitted() throws RateLimitExceededException {
when(challengeConstraintChecker.challengeConstraintsGrpc(account))
.thenReturn(new ChallengeConstraintChecker.ChallengeConstraints(false, Optional.empty()));
when(rateLimitChallengeManager.answerPushChallenge(account, "foo")).thenReturn(true);
final StatusRuntimeException statusRuntimeException = assertThrows(StatusRuntimeException.class,
() -> authenticatedServiceStub().answerChallenge(
AnswerChallengeRequest.newBuilder()
.setToken("token")
.setPush(AnswerChallengeRequest.AnswerPushChallengeRequest.newBuilder()
.setChallenge("foo")
.build())
.build()));
assertEquals(Status.RESOURCE_EXHAUSTED.getCode(), statusRuntimeException.getStatus().getCode());
verify(rateLimitChallengeManager, never()).answerPushChallenge(any(), any());
}
@Test
@@ -74,8 +101,10 @@ public class ChallengeGrpcServiceTest extends
final Duration retryAfter = Duration.ofMinutes(1);
doThrow(new RateLimitExceededException(retryAfter)).when(rateLimitChallengeManager)
.answerPushChallenge(account, "foo");
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertRateLimitExceeded(retryAfter,
() -> authenticatedServiceStub().handleChallengeResponse(AnswerChallengeRequest.newBuilder()
() -> authenticatedServiceStub().answerChallenge(AnswerChallengeRequest.newBuilder()
.setToken("token")
.setPush(AnswerChallengeRequest.AnswerPushChallengeRequest.newBuilder()
.setChallenge("foo")
@@ -91,7 +120,7 @@ public class ChallengeGrpcServiceTest extends
new ChallengeConstraintChecker.ChallengeConstraints(true, Optional.empty()));
when(rateLimitChallengeManager.answerCaptchaChallenge(any(), any(), any(), any(), any())).thenReturn(
captchaSuccess);
final AnswerChallengeResponse response = authenticatedServiceStub().handleChallengeResponse(
final AnswerChallengeResponse response = authenticatedServiceStub().answerChallenge(
AnswerChallengeRequest.newBuilder()
.setToken("token")
.setCaptcha(AnswerChallengeRequest.AnswerCaptchaChallengeRequest.newBuilder()
@@ -109,8 +138,10 @@ public class ChallengeGrpcServiceTest extends
final Duration retryAfter = Duration.ofMinutes(1);
doThrow(new RateLimitExceededException(retryAfter)).when(rateLimitChallengeManager)
.answerCaptchaChallenge(any(), any(), any(), any(), any());
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertRateLimitExceeded(retryAfter,
() -> authenticatedServiceStub().handleChallengeResponse(AnswerChallengeRequest.newBuilder()
() -> authenticatedServiceStub().answerChallenge(AnswerChallengeRequest.newBuilder()
.setToken("token")
.setCaptcha(AnswerChallengeRequest.AnswerCaptchaChallengeRequest.newBuilder()
.setCaptcha("captcha")
@@ -123,7 +154,7 @@ public class ChallengeGrpcServiceTest extends
when(challengeConstraintChecker.challengeConstraintsGrpc(account)).thenReturn(
new ChallengeConstraintChecker.ChallengeConstraints(true, Optional.empty()));
GrpcTestUtils.assertStatusInvalidArgument(
() -> authenticatedServiceStub().handleChallengeResponse(AnswerChallengeRequest.newBuilder().build()));
() -> authenticatedServiceStub().answerChallenge(AnswerChallengeRequest.newBuilder().build()));
}
@Test
@@ -131,7 +162,7 @@ public class ChallengeGrpcServiceTest extends
when(challengeConstraintChecker.challengeConstraintsGrpc(account)).thenReturn(
new ChallengeConstraintChecker.ChallengeConstraints(true, Optional.empty()));
GrpcTestUtils.assertStatusInvalidArgument(
() -> authenticatedServiceStub().handleChallengeResponse(AnswerChallengeRequest.newBuilder()
() -> authenticatedServiceStub().answerChallenge(AnswerChallengeRequest.newBuilder()
.setPush(AnswerChallengeRequest.AnswerPushChallengeRequest.newBuilder()
.build())
.build()));
@@ -142,7 +173,7 @@ public class ChallengeGrpcServiceTest extends
when(challengeConstraintChecker.challengeConstraintsGrpc(account)).thenReturn(
new ChallengeConstraintChecker.ChallengeConstraints(true, Optional.empty()));
GrpcTestUtils.assertStatusInvalidArgument(
() -> authenticatedServiceStub().handleChallengeResponse(AnswerChallengeRequest.newBuilder()
() -> authenticatedServiceStub().answerChallenge(AnswerChallengeRequest.newBuilder()
.setToken("token")
.setPush(AnswerChallengeRequest.AnswerPushChallengeRequest.newBuilder()
.build())
@@ -154,10 +185,49 @@ public class ChallengeGrpcServiceTest extends
when(challengeConstraintChecker.challengeConstraintsGrpc(account)).thenReturn(
new ChallengeConstraintChecker.ChallengeConstraints(true, Optional.empty()));
GrpcTestUtils.assertStatusInvalidArgument(
() -> authenticatedServiceStub().handleChallengeResponse(AnswerChallengeRequest.newBuilder()
() -> authenticatedServiceStub().answerChallenge(AnswerChallengeRequest.newBuilder()
.setToken("token")
.setCaptcha(AnswerChallengeRequest.AnswerCaptchaChallengeRequest.newBuilder()
.build())
.build()));
}
@Test
void requestPushChallenge() throws NotPushRegisteredException {
when(challengeConstraintChecker.challengeConstraintsGrpc(account)).thenReturn(
new ChallengeConstraintChecker.ChallengeConstraints(true, Optional.empty()));
final RequestPushChallengeResponse response =
authenticatedServiceStub().requestPushChallenge(RequestPushChallengeRequest.getDefaultInstance());
assertEquals(RequestPushChallengeResponse.ResponseCase.SENT_PUSH_CHALLENGE, response.getResponseCase());
verify(rateLimitChallengeManager).sendPushChallenge(account);
}
@Test
void requestPushChallengeNotPermitted() throws NotPushRegisteredException {
when(challengeConstraintChecker.challengeConstraintsGrpc(account)).thenReturn(
new ChallengeConstraintChecker.ChallengeConstraints(false, Optional.empty()));
final StatusRuntimeException statusRuntimeException = assertThrows(StatusRuntimeException.class, () ->
authenticatedServiceStub().requestPushChallenge(RequestPushChallengeRequest.getDefaultInstance()));
assertEquals(Status.RESOURCE_EXHAUSTED.getCode(), statusRuntimeException.getStatus().getCode());
verify(rateLimitChallengeManager, never()).sendPushChallenge(any());
}
@Test
void requestPushChallengeNoPushToken() throws NotPushRegisteredException {
when(challengeConstraintChecker.challengeConstraintsGrpc(account)).thenReturn(
new ChallengeConstraintChecker.ChallengeConstraints(true, Optional.empty()));
doThrow(NotPushRegisteredException.class)
.when(rateLimitChallengeManager).sendPushChallenge(any());
final RequestPushChallengeResponse response =
authenticatedServiceStub().requestPushChallenge(RequestPushChallengeRequest.getDefaultInstance());
assertEquals(RequestPushChallengeResponse.ResponseCase.NO_PUSH_TOKEN, response.getResponseCase());
}
}
@@ -48,8 +48,8 @@ import org.mockito.Mock;
import org.mockito.Mockito;
import org.signal.chat.credentials.CredentialsGrpc;
import org.signal.chat.credentials.ExternalServiceType;
import org.signal.chat.credentials.GetCreateCallLinkCredentialsRequest;
import org.signal.chat.credentials.GetCreateCallLinkCredentialsResponse;
import org.signal.chat.credentials.GetCreateCallLinkCredentialRequest;
import org.signal.chat.credentials.GetCreateCallLinkCredentialResponse;
import org.signal.chat.credentials.GetDeliveryCertificateRequest;
import org.signal.chat.credentials.GetDeliveryCertificateResponse;
import org.signal.chat.credentials.GetExternalServiceCredentialsRequest;
@@ -348,8 +348,8 @@ public class CredentialsGrpcServiceTest
for (int i = 0; i < redemptionEndOffsetDays; i++) {
final Instant redemptionTime = startOfDay.plus(Duration.ofDays(i));
assertEquals(redemptionTime.getEpochSecond(), response.getGroupCredentials(i).getRedemptionTimeSeconds());
assertEquals(redemptionTime.getEpochSecond(), response.getCallLinkAuthCredentials(i).getRedemptionTimeSeconds());
assertEquals(redemptionTime.getEpochSecond(), response.getGroupCredentials(i).getRedemptionTime());
assertEquals(redemptionTime.getEpochSecond(), response.getCallLinkAuthCredentials(i).getRedemptionTime());
final int index = i;
@@ -406,14 +406,13 @@ public class CredentialsGrpcServiceTest
final byte[] roomId = TestRandomUtil.nextBytes(32);
final GetCreateCallLinkCredentialsResponse response =
authenticatedServiceStub().getCreateCallLinkCredentials(GetCreateCallLinkCredentialsRequest.newBuilder()
final GetCreateCallLinkCredentialResponse response =
authenticatedServiceStub().getCreateCallLinkCredential(GetCreateCallLinkCredentialRequest.newBuilder()
.setCredentialRequest(
ByteString.copyFrom(CreateCallLinkCredentialRequestContext.forRoom(roomId).getRequest().serialize()))
.build());
assertFalse(response.getCredential().isEmpty());
assertEquals(CLOCK.instant().truncatedTo(ChronoUnit.DAYS).getEpochSecond(), response.getRedemptionTimeSeconds());
}
@Test
@@ -427,7 +426,7 @@ public class CredentialsGrpcServiceTest
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertRateLimitExceeded(retryAfter,
() -> authenticatedServiceStub().getCreateCallLinkCredentials(GetCreateCallLinkCredentialsRequest.newBuilder()
() -> authenticatedServiceStub().getCreateCallLinkCredential(GetCreateCallLinkCredentialRequest.newBuilder()
.setCredentialRequest(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build()));
}
@@ -437,7 +436,7 @@ public class CredentialsGrpcServiceTest
when(rateLimiters.getCreateCallLinkLimiter()).thenReturn(mock(RateLimiter.class));
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().getCreateCallLinkCredentials(GetCreateCallLinkCredentialsRequest.newBuilder()
() -> authenticatedServiceStub().getCreateCallLinkCredential(GetCreateCallLinkCredentialRequest.newBuilder()
.setCredentialRequest(ByteString.copyFrom(TestRandomUtil.nextBytes(16)))
.build()));
}
@@ -5,10 +5,14 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import com.google.rpc.ErrorInfo;
import io.grpc.Channel;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.protobuf.StatusProto;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
@@ -32,7 +36,6 @@ import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.List;
@@ -40,6 +43,8 @@ import java.util.Optional;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -54,6 +59,7 @@ import static org.whispersystems.textsecuregcm.controllers.KeyTransparencyContro
import static org.whispersystems.textsecuregcm.controllers.KeyTransparencyControllerTest.USERNAME_HASH;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertRateLimitExceeded;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusException;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.extractErrorInfo;
import static org.whispersystems.textsecuregcm.grpc.KeyTransparencyGrpcService.COMMITMENT_INDEX_LENGTH;
@SuppressWarnings({"OptionalUsedAsFieldOrParameterType", "ResultOfMethodCallIgnored"})
@@ -63,6 +69,9 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
@Mock
private RateLimiter rateLimiter;
// The key transparency service uses a different domain from the chat server.
private static final String KEY_TRANSPARENCY_DOMAIN = "key-transparency";
@Override
protected KeyTransparencyGrpcService createServiceBeforeEachTest() {
final RateLimiters rateLimiters = mock(RateLimiters.class);
@@ -79,9 +88,8 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
}
@Test
void searchSuccess() throws RateLimitExceededException {
void searchSuccess() {
when(keyTransparencyServiceClient.search(any())).thenReturn(SearchResponseV2.getDefaultInstance());
Mockito.doNothing().when(rateLimiter).validate(any(String.class));
final SearchRequest request = SearchRequest.newBuilder()
.setAci(ByteString.copyFrom(ACI.toCompactByteArray()))
.setAciIdentityKey(ByteString.copyFrom(ACI_IDENTITY_KEY.serialize()))
@@ -156,11 +164,38 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
verifyNoInteractions(keyTransparencyServiceClient);
}
@Test
void overrideBackingServiceErrorDomain() {
final StatusRuntimeException keyTransparencyException = StatusProto.toStatusRuntimeException(
com.google.rpc.Status.newBuilder()
.setCode(Status.Code.UNAVAILABLE.value())
.addDetails(Any.pack(ErrorInfo.newBuilder()
.setDomain(KEY_TRANSPARENCY_DOMAIN)
.setReason("UNAVAILABLE")
.build()))
.build());
when(keyTransparencyServiceClient.search(any())).thenThrow(keyTransparencyException);
final SearchRequest request = SearchRequest.newBuilder()
.setAci(ByteString.copyFrom(ACI.toCompactByteArray()))
.setAciIdentityKey(ByteString.copyFrom(ACI_IDENTITY_KEY.serialize()))
.setConsistency(ConsistencyParameters.newBuilder()
.setDistinguished(10)
.build())
.build();
final StatusRuntimeException exception =
assertThrows(StatusRuntimeException.class, () -> unauthenticatedServiceStub().searchV2(request));
assertEquals(GrpcExceptions.DOMAIN, extractErrorInfo(exception).getDomain(),
"errors from the key transparency service must report the chat server's error domain");
}
@Test
void monitorSuccess() {
when(keyTransparencyServiceClient.monitor(any())).thenReturn(MonitorResponseV2.getDefaultInstance());
when(rateLimiter.validateReactive(any(String.class)))
.thenReturn(Mono.empty());
final AciMonitorRequest aciMonitorRequest = AciMonitorRequest.newBuilder()
.setAci(ByteString.copyFrom(ACI.toCompactByteArray()))
.setCommitmentIndex(ByteString.copyFrom(new byte[COMMITMENT_INDEX_LENGTH]))
@@ -250,8 +285,6 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
@Test
void distinguishedSuccess() {
when(keyTransparencyServiceClient.distinguished(any())).thenReturn(DistinguishedResponse.getDefaultInstance());
when(rateLimiter.validateReactive(any(String.class)))
.thenReturn(Mono.empty());
final DistinguishedRequest request = DistinguishedRequest.newBuilder().build();
assertDoesNotThrow(() -> unauthenticatedServiceStub().distinguishedV2(request));
@@ -12,6 +12,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
@@ -30,6 +31,7 @@ import io.grpc.StatusRuntimeException;
import io.grpc.stub.BlockingClientCall;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -38,7 +40,6 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
@@ -56,6 +57,7 @@ import org.signal.chat.messages.GetMessagesResponse;
import org.signal.chat.messages.IndividualRecipientMessageBundle;
import org.signal.chat.messages.MessagesGrpc;
import org.signal.chat.messages.MismatchedDevices;
import org.signal.chat.messages.ReportMessageRequest;
import org.signal.chat.messages.SendAuthenticatedSenderMessageRequest;
import org.signal.chat.messages.SendMessageAuthenticatedSenderResponse;
import org.signal.chat.messages.SendMessageType;
@@ -66,7 +68,7 @@ import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
@@ -80,6 +82,8 @@ import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@@ -92,6 +96,12 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
@Mock
private AccountsManager accountsManager;
@Mock
private ReportMessageManager reportMessageManager;
@Mock
private PhoneNumberIdentifiers phoneNumberIdentifiers;
@Mock
private RateLimiters rateLimiters;
@@ -140,6 +150,8 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
@Override
protected MessagesGrpcService createServiceBeforeEachTest() {
return new MessagesGrpcService(accountsManager,
reportMessageManager,
phoneNumberIdentifiers,
rateLimiters,
messageSender,
messageByteLimitEstimator,
@@ -378,7 +390,6 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
.setType(SendMessageType.DOUBLE_RATCHET)
.build());
//noinspection ResultOfMethodCallIgnored
assertRateLimitExceeded(retryDuration,
() -> authenticatedServiceStub().sendMessage(
generateRequest(serviceIdentifier, false, true, messages)));
@@ -682,7 +693,6 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
.setType(SendMessageType.DOUBLE_RATCHET)
.build());
//noinspection ResultOfMethodCallIgnored
assertRateLimitExceeded(retryDuration, () ->
authenticatedServiceStub().sendSyncMessage(generateRequest(true, messages)));
@@ -719,7 +729,6 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
@Test
void messageDeliveryNotAllowed()
throws MessageTooLargeException, MessageDeliveryNotAllowedException, MismatchedDevicesException {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(AUTHENTICATED_ACI);
final byte[] payload = TestRandomUtil.nextBytes(128);
final Map<Byte, IndividualRecipientMessageBundle.Message> messages =
@@ -783,7 +792,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
@ParameterizedTest
@MethodSource
void invalidAckMessages(final GetMessagesRequest request)
throws StatusException, InterruptedException, TimeoutException {
throws StatusException, InterruptedException {
doAnswer(invocation -> {
Flux<UUID> ackArg = invocation.getArgument(4);
// use mapNotNull instead of `then` because there is an interaction between the blocking client and
@@ -793,7 +802,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
}).when(messageDispatcher).getMessages(anyBoolean(), any(), any(), any(), any());
final BlockingClientCall<GetMessagesRequest, GetMessagesResponse> blockingCall = authenticatedServiceStub().getMessages();
final CompletableFuture<StatusException> reader = CompletableFuture.supplyAsync(() -> assertThrows(StatusException.class, () -> blockingCall.read()));
final CompletableFuture<StatusException> reader = CompletableFuture.supplyAsync(() -> assertThrows(StatusException.class, blockingCall::read));
blockingCall.write(GetMessagesRequest.newBuilder().setOptions(GetMessagesRequest.GetMessageOptions.getDefaultInstance()).build());
blockingCall.write(request);
@@ -814,6 +823,55 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
}
}
@Timeout(value = 1, unit = TimeUnit.MINUTES, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
@Nested
class ReportMessage {
@Test
void reportMessage() throws StatusException {
final AciServiceIdentifier sourceServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final UUID messageGuid = UUID.randomUUID();
final byte[] reportSpamToken = TestRandomUtil.nextBytes(128);
//noinspection ResultOfMethodCallIgnored
authenticatedServiceStub().reportMessage(ReportMessageRequest.newBuilder()
.setSourceServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(sourceServiceIdentifier))
.setMessageGuid(UUIDUtil.toByteString(messageGuid))
.setReportSpamToken(ByteString.copyFrom(reportSpamToken))
.build());
verify(reportMessageManager).report(eq(Optional.empty()),
eq(sourceServiceIdentifier.uuid()),
eq(Optional.empty()),
eq(messageGuid),
eq(AUTHENTICATED_ACI),
argThat(maybeToken -> maybeToken.map(token -> Arrays.equals(token, reportSpamToken)).orElse(false)),
any(),
eq(true));
}
@Test
void reportMessageNoToken() throws StatusException {
final AciServiceIdentifier sourceServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final UUID messageGuid = UUID.randomUUID();
//noinspection ResultOfMethodCallIgnored
authenticatedServiceStub().reportMessage(ReportMessageRequest.newBuilder()
.setSourceServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(sourceServiceIdentifier))
.setMessageGuid(UUIDUtil.toByteString(messageGuid))
.build());
verify(reportMessageManager).report(eq(Optional.empty()),
eq(sourceServiceIdentifier.uuid()),
eq(Optional.empty()),
eq(messageGuid),
eq(AUTHENTICATED_ACI),
eq(Optional.empty()),
any(),
eq(true));
}
}
private static ThrowingSupplier<?> convertStatusException(final ThrowingSupplier<?> serviceCall) {
return () -> {
try {
@@ -20,7 +20,7 @@ class H2FrameProxyHandlerTest {
@Test
void proxyWritabilityChanged() {
final EmbeddedChannel target = new EmbeddedChannel();
final EmbeddedChannel source = new EmbeddedChannel(new H2FrameProxyHandler(target, "test"));
final EmbeddedChannel source = new EmbeddedChannel(new H2FrameProxyHandler(target, "test", "test-backend"));
// Set a tiny watermark to guarantee an unflushed write sets to unwritable, and then buffer some data
final byte[] bufferedData = "8 bytes!".getBytes(StandardCharsets.UTF_8);
@@ -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;
}
}
@@ -0,0 +1,78 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.UUID;
import java.util.stream.IntStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
class ConcatenatingMessageStreamTest {
private RedisDynamoDbMessageStream redisDynamoDbMessageStream;
private FoundationDbMessageStream foundationDbMessageStream;
private ConcatenatingMessageStream concatenatingMessageStream;
@BeforeEach
void setUp() {
redisDynamoDbMessageStream = mock(RedisDynamoDbMessageStream.class);
foundationDbMessageStream = mock(FoundationDbMessageStream.class);
concatenatingMessageStream = new ConcatenatingMessageStream(redisDynamoDbMessageStream, foundationDbMessageStream);
}
@Test
void getMessages() {
final int messageCount = 3;
final List<? extends MessageStreamEntry> messageStreamEntries = IntStream.range(0, messageCount)
.mapToObj(i -> new MessageStreamEntry.Envelope(MessageProtos.Envelope.newBuilder().setServerTimestamp(i).build()))
.toList();
for (int i = 0; i < messageCount; i++) {
when(redisDynamoDbMessageStream.getMessages())
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(messageStreamEntries.subList(0, i))));
when(foundationDbMessageStream.getMessages())
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(messageStreamEntries.subList(i, messageStreamEntries.size()))));
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(concatenatingMessageStream.getMessages()))
.expectNextSequence(messageStreamEntries)
.expectComplete()
.verify();
}
}
@Test
void acknowledgeMessage() {
final UUID v4Uuid = UUID.randomUUID();
final long serverTimestamp = System.currentTimeMillis();
concatenatingMessageStream.acknowledgeMessage(v4Uuid, serverTimestamp).join();
verify(redisDynamoDbMessageStream).acknowledgeMessage(v4Uuid, serverTimestamp);
verify(foundationDbMessageStream, never()).acknowledgeMessage(eq(v4Uuid), anyLong());
final UUID v8Uuid = MessageGuidUtil.generateRandomV8UUID();
concatenatingMessageStream.acknowledgeMessage(v8Uuid, serverTimestamp).join();
verify(redisDynamoDbMessageStream).acknowledgeMessage(v8Uuid, serverTimestamp);
verify(foundationDbMessageStream).acknowledgeMessage(v8Uuid, serverTimestamp);
}
}
@@ -112,7 +112,7 @@ class RedisDynamoDbMessagePublisherTest {
final UUID accountIdentifier = UUID.randomUUID();
final RedisDynamoDbMessagePublisher _ =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device);
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device, false);
verify(redisMessageAvailabilityManager, never()).handleClientConnected(eq(accountIdentifier), eq(deviceId), any());
verify(redisMessageAvailabilityManager, never()).handleClientDisconnected(eq(accountIdentifier), eq(deviceId), any());
@@ -122,7 +122,7 @@ class RedisDynamoDbMessagePublisherTest {
final UUID accountIdentifier = UUID.randomUUID();
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device);
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device, false);
JdkFlowAdapter.flowPublisherToFlux(messagePublisher).subscribe();
@@ -134,7 +134,7 @@ class RedisDynamoDbMessagePublisherTest {
final UUID accountIdentifier = UUID.randomUUID();
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device);
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device, false);
final Disposable disposable = JdkFlowAdapter.flowPublisherToFlux(messagePublisher).subscribe();
disposable.dispose();
@@ -150,7 +150,7 @@ class RedisDynamoDbMessagePublisherTest {
final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage());
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false);
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher))
.expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage))
@@ -159,12 +159,43 @@ class RedisDynamoDbMessagePublisherTest {
.verifyTimeout(Duration.ofMillis(500));
}
@Test
void publishMessagesTerminateOnEmpty() {
final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage());
final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage());
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, true);
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher))
.expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage))
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
.expectNoEvent(Duration.ofMillis(100))
.then(() -> {
// Acknowledge the DynamoDB message and the Redis message
messagePublisher.handleMessageAcknowledged();
messagePublisher.handleMessageAcknowledged();
})
.expectComplete()
.verify();
}
@Test
void publishMessagesTerminateNoMessages() {
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, true);
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher))
.expectComplete()
.verify();
}
@Test
void publishMessagesDynamoDbOnly() {
final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage());
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false);
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher))
.expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage))
@@ -177,7 +208,7 @@ class RedisDynamoDbMessagePublisherTest {
final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage());
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false);
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher))
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
@@ -193,7 +224,7 @@ class RedisDynamoDbMessagePublisherTest {
final MessageProtos.Envelope newArrivalRedisMessage = generateRandomMessage();
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false);
final CountDownLatch queueEmptyCountDownLatch = new CountDownLatch(1);
@@ -235,7 +266,7 @@ class RedisDynamoDbMessagePublisherTest {
final MessageProtos.Envelope persistedMessage = generateRandomMessage();
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false);
final CountDownLatch queueEmptyCountDownLatch = new CountDownLatch(1);
@@ -277,7 +308,7 @@ class RedisDynamoDbMessagePublisherTest {
final MessageProtos.Envelope persistedMessage = generateRandomMessage();
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false);
final CountDownLatch queueEmptyCountDownLatch = new CountDownLatch(1);
@@ -307,7 +338,7 @@ class RedisDynamoDbMessagePublisherTest {
@Test
void publishMessagesConsumerConflict() {
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false);
final CountDownLatch countDownLatch = new CountDownLatch(1);
@@ -348,7 +379,7 @@ class RedisDynamoDbMessagePublisherTest {
}
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false);
final List<MessageProtos.Envelope> publishedMessages = new ArrayList<>(expectedMessages.size());
@@ -377,7 +408,7 @@ class RedisDynamoDbMessagePublisherTest {
{
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false);
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher), 1)
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
@@ -387,7 +418,7 @@ class RedisDynamoDbMessagePublisherTest {
{
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false);
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher), 2)
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
@@ -79,13 +79,13 @@ class ReportMessageManagerTest {
reportMessageManager.addListener(listener);
when(reportMessageDynamoDb.remove(any())).thenReturn(false);
reportMessageManager.report(Optional.of(sourceNumber), Optional.of(sourceAci), Optional.of(sourcePni), messageGuid,
reportMessageManager.report(Optional.of(sourceNumber), sourceAci, Optional.of(sourcePni), messageGuid,
reporterUuid, Optional.empty(), "user-agent", false);
assertEquals(0, reportMessageManager.getRecentReportCount(sourceAccount));
when(reportMessageDynamoDb.remove(any())).thenReturn(true);
reportMessageManager.report(Optional.of(sourceNumber), Optional.of(sourceAci), Optional.of(sourcePni), messageGuid,
reportMessageManager.report(Optional.of(sourceNumber), sourceAci, Optional.of(sourcePni), messageGuid,
reporterUuid, Optional.empty(), "user-agent", false);
assertEquals(1, reportMessageManager.getRecentReportCount(sourceAccount));
@@ -98,7 +98,7 @@ class ReportMessageManagerTest {
assertEquals(0, reportMessageManager.getRecentReportCount(sourceAccount));
for (int i = 0; i < 100; i++) {
reportMessageManager.report(Optional.of(sourceNumber), Optional.of(sourceAci), Optional.of(sourcePni),
reportMessageManager.report(Optional.of(sourceNumber), sourceAci, Optional.of(sourcePni),
messageGuid, UUID.randomUUID(), Optional.empty(), "user-agent", false);
}
@@ -111,7 +111,7 @@ class ReportMessageManagerTest {
assertEquals(0, reportMessageManager.getRecentReportCount(sourceAccount));
for (int i = 0; i < 100; i++) {
reportMessageManager.report(Optional.of(sourceNumber), Optional.of(sourceAci), Optional.of(sourcePni),
reportMessageManager.report(Optional.of(sourceNumber), sourceAci, Optional.of(sourcePni),
messageGuid,
reporterUuid, Optional.empty(), "user-agent", false);
}
@@ -125,11 +125,11 @@ class ReportMessageManagerTest {
assertEquals(0, reportMessageManager.getRecentReportCount(sourceAccount));
for (int i = 0; i < 100; i++) {
reportMessageManager.report(Optional.empty(), Optional.of(sourceAci), Optional.of(sourcePni),
reportMessageManager.report(Optional.empty(), sourceAci, Optional.of(sourcePni),
messageGuid, UUID.randomUUID(), Optional.empty(), "user-agent", false);
}
reportMessageManager.report(Optional.empty(), Optional.of(sourceAci), Optional.empty(),
reportMessageManager.report(Optional.empty(), sourceAci, Optional.empty(),
messageGuid, UUID.randomUUID(), Optional.empty(), "user-agent", false);
final int recentReportCount = reportMessageManager.getRecentReportCount(sourceAccount);
@@ -4,18 +4,17 @@
*/
package org.whispersystems.textsecuregcm.tests.util;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
import com.google.protobuf.InvalidProtocolBufferException;
import org.eclipse.jetty.websocket.api.Callback;
import org.eclipse.jetty.websocket.api.Session;
import org.slf4j.Logger;
@@ -50,8 +49,9 @@ public class TestWebsocketListener implements Session.Listener.AutoDemanding {
}
@Override
public void onWebSocketClose(int statusCode, String reason) {
public void onWebSocketClose(int statusCode, String reason, Callback callback) {
closed.complete(statusCode);
callback.succeed();
}
public CompletableFuture<Integer> closeFuture() {
@@ -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
@@ -72,7 +72,7 @@ public class WebSocketSessionContext {
}
public interface WebSocketEventListener {
public void onWebSocketClose(WebSocketSessionContext context, int statusCode, String reason);
void onWebSocketClose(WebSocketSessionContext context, int statusCode, String reason);
}