Compare commits

...
Author SHA1 Message Date
Chris Eager 1e2d27585a Add gRPC size annotations; allow non-empty UAK for unrestricted 2026-04-16 13:18:56 -05:00
Chris Eager c70674ed26 Update serialization test 2026-04-16 13:18:56 -05:00
Chris Eager 0281756c01 Add metrics for invalid unrestricted UAK 2026-04-16 13:18:56 -05:00
Chris Eager 5e1338a571 Factor out DeviceAttributes from AccountAttributes 2026-04-16 13:18:56 -05:00
Chris Eager 149de6c464 Add UAK validator to AccountAttributes 2026-04-16 13:18:56 -05:00
Chris Eager b551e0cb34 Require UAKs to be non-zero length or null 2026-04-16 13:18:56 -05:00
Chris Eager 2344d3d9b7 Add AccountAttributes serialization test 2026-04-16 13:18:56 -05:00
Chris Eager 04aa528ad8 Add Accounts.SetZkCredentialKey 2026-04-16 12:13:34 -05:00
Jon Chambers 1b5c602351 Retire the device count override system 2026-04-16 12:52:15 -04:00
Ravi Khadiwala bbeeed9d1f Remove unused static grpcAllowList configuration 2026-04-15 18:05:06 -04:00
Chris Eager aabbbe486f Update exception for empty non-sync messages to MessageSender 2026-04-15 17:03:10 -05:00
Jon Chambers b702d9d5a9 Remove service level objectives for captcha outcome distribution 2026-04-15 18:01:59 -04:00
Jon Chambers efc39573e4 Use CaptchaMetrics to measure captcha scores for sending messages and verification 2026-04-15 16:40:06 -04:00
Jon Chambers 87e88dd3a1 Introduce CaptchaMetrics 2026-04-15 16:40:06 -04:00
Chris Eager 4ae82cbb59 Add @NotEmpty validation to IncomingMessageList 2026-04-15 16:38:19 -04:00
Jon Chambers dcb5187629 Retire V1 authentication tokens 2026-04-15 16:37:52 -04:00
Jon Chambers bb589d6daa Retire AccountsManager#updateDeviceAuthentication 2026-04-15 16:37:52 -04:00
Ameya Lokare bb7d855aca Prevent reg lock bypass on alternate phone number forms 2026-04-15 16:37:18 -04:00
Ameya Lokare 288b9f82d7 Prevent potentially orphaned usernames due to concurrent username
confirmation during account deletion
2026-04-15 16:36:41 -04:00
Ameya Lokare 61f5998e8a Add rate limiter to batch profile check 2026-04-15 16:35:24 -04:00
42 changed files with 610 additions and 329 deletions

No files matched your search

@@ -130,8 +130,8 @@ public class TestUser {
public AccountAttributes accountAttributes() {
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)
.withUnidentifiedAccessKey(unidentifiedAccessKey)
.withRecoveryPassword(registrationPassword);
.setUnidentifiedAccessKey(unidentifiedAccessKey)
.setRecoveryPassword(registrationPassword);
}
public void setAciUuid(final UUID aciUuid) {
@@ -10,9 +10,6 @@ import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
@@ -32,7 +29,6 @@ import org.whispersystems.textsecuregcm.configuration.DeviceCheckConfiguration;
import org.whispersystems.textsecuregcm.configuration.DirectoryV2Configuration;
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory;
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcAllowListConfiguration;
import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfiguration;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory;
@@ -45,7 +41,6 @@ import org.whispersystems.textsecuregcm.configuration.HlrLookupConfiguration;
import org.whispersystems.textsecuregcm.configuration.IdlePrimaryDeviceReminderConfiguration;
import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
import org.whispersystems.textsecuregcm.configuration.MaxDeviceConfiguration;
import org.whispersystems.textsecuregcm.configuration.MessageByteLimitCardinalityEstimatorConfiguration;
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
@@ -188,11 +183,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private MessageCacheConfiguration messageCache;
@Valid
@NotNull
@JsonProperty
private List<MaxDeviceConfiguration> maxDevices = new LinkedList<>();
@Valid
@NotNull
@JsonProperty
@@ -355,11 +345,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private GrpcConfiguration grpc;
@NotNull
@Valid
@JsonProperty
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
@Valid
@NotNull
@JsonProperty
@@ -486,17 +471,6 @@ public class WhisperServerConfiguration extends Configuration {
return unidentifiedDelivery;
}
public Map<String, Integer> getMaxDevices() {
Map<String, Integer> results = new HashMap<>();
for (MaxDeviceConfiguration maxDeviceConfiguration : maxDevices) {
results.put(maxDeviceConfiguration.getNumber(),
maxDeviceConfiguration.getCount());
}
return results;
}
public PaymentsServiceConfiguration getPaymentsServiceConfiguration() {
return paymentsService;
}
@@ -605,10 +579,6 @@ public class WhisperServerConfiguration extends Configuration {
return grpc;
}
public DynamicGrpcAllowListConfiguration getGrpcAllowList() {
return grpcAllowList;
}
public S3ObjectMonitorFactory getAsnTableConfiguration() {
return asnTable;
}
@@ -1105,7 +1105,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays(), config.getDeliveryCertificate().embedSigner()),
zkAuthOperations, callingGenericZkSecretParams, clock),
new ChallengeController(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DeviceController(accountsManager, rateLimiters, persistentTimer, config.getMaxDevices()),
new DeviceController(accountsManager, rateLimiters, persistentTimer),
new DeviceCheckController(clock, accountsManager, backupAuthManager, appleDeviceCheckManager, rateLimiters,
config.getDeviceCheck().backupRedemptionLevel(),
config.getDeviceCheck().backupRedemptionDuration()),
@@ -10,7 +10,6 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Authenticator;
import io.dropwizard.auth.basic.BasicCredentials;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.time.Clock;
@@ -36,9 +35,6 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
private static final String DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME = name(AccountAuthenticator.class, "daysSinceLastSeen");
private static final String IS_PRIMARY_DEVICE_TAG = "isPrimary";
private static final Counter OLD_TOKEN_VERSION_COUNTER =
Metrics.counter(name(AccountAuthenticator.class, "oldTokenVersionCounter"));
@VisibleForTesting
static final char DEVICE_ID_SEPARATOR = '.';
@@ -104,14 +100,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
SaltedTokenHash deviceSaltedTokenHash = device.get().getAuthTokenHash();
if (deviceSaltedTokenHash.verify(basicCredentials.getPassword())) {
succeeded = true;
Account authenticatedAccount = updateLastSeen(account.get(), device.get());
if (deviceSaltedTokenHash.getVersion() != SaltedTokenHash.CURRENT_VERSION) {
OLD_TOKEN_VERSION_COUNTER.increment();
authenticatedAccount = accountsManager.updateDeviceAuthentication(
authenticatedAccount,
device.get(),
SaltedTokenHash.generateFor(basicCredentials.getPassword())); // new credentials have current version
}
final Account authenticatedAccount = updateLastSeen(account.get(), device.get());
return Optional.of(new AuthenticatedDevice(authenticatedAccount.getIdentifier(IdentityType.ACI),
device.get().getId(),
Instant.ofEpochMilli(authenticatedAccount.getPrimaryDevice().getLastSeen())));
@@ -16,6 +16,9 @@ public class Anonymous {
public Anonymous(String header) {
try {
this.unidentifiedSenderAccessKey = Base64.getDecoder().decode(header);
if (unidentifiedSenderAccessKey.length != UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH) {
throw new WebApplicationException("access key length must be 16", Response.Status.UNAUTHORIZED);
}
} catch (IllegalArgumentException e) {
throw new WebApplicationException(e, Response.Status.UNAUTHORIZED);
}
@@ -6,20 +6,12 @@ package org.whispersystems.textsecuregcm.auth;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HexFormat;
import org.signal.libsignal.protocol.kdf.HKDF;
public record SaltedTokenHash(String hash, String salt) {
public enum Version {
V1,
V2,
}
public static final Version CURRENT_VERSION = Version.V2;
private static final String V2_PREFIX = "2.";
private static final byte[] AUTH_TOKEN_HKDF_INFO = "authtoken".getBytes(StandardCharsets.UTF_8);
@@ -31,21 +23,13 @@ public record SaltedTokenHash(String hash, String salt) {
public static SaltedTokenHash generateFor(final String token) {
final String salt = generateSalt();
final String hash = calculateV2Hash(salt, token);
final String hash = calculateHash(salt, token);
return new SaltedTokenHash(hash, salt);
}
public Version getVersion() {
return hash.startsWith(V2_PREFIX) ? Version.V2 : Version.V1;
}
public boolean verify(final String token) {
final String theirValue = switch (getVersion()) {
case V1 -> calculateV1Hash(salt, token);
case V2 -> calculateV2Hash(salt, token);
};
return MessageDigest.isEqual(
theirValue.getBytes(StandardCharsets.UTF_8),
calculateHash(salt, token).getBytes(StandardCharsets.UTF_8),
hash.getBytes(StandardCharsets.UTF_8));
}
@@ -55,16 +39,7 @@ public record SaltedTokenHash(String hash, String salt) {
return HexFormat.of().formatHex(salt);
}
private static String calculateV1Hash(final String salt, final String token) {
try {
return HexFormat.of()
.formatHex(MessageDigest.getInstance("SHA1").digest((salt + token).getBytes(StandardCharsets.UTF_8)));
} catch (final NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
private static String calculateV2Hash(final String salt, final String token) {
private static String calculateHash(final String salt, final String token) {
final byte[] secret = HKDF.deriveSecrets(
token.getBytes(StandardCharsets.UTF_8), // key
salt.getBytes(StandardCharsets.UTF_8), // salt
@@ -93,6 +93,9 @@ public class AssessmentResult {
return this.actualScore;
}
public int getNormalizedIntScore() {
return normalizedIntScore(this.actualScore);
}
/**
* Map a captcha score in [0.0, 1.0] to a low cardinality discrete space in [0, 100] suitable for use in metrics
@@ -1,30 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
public class MaxDeviceConfiguration {
@JsonProperty
@NotEmpty
private String number;
@JsonProperty
@NotNull
private int count;
public String getNumber() {
return number;
}
public int getCount() {
return count;
}
}
@@ -50,8 +50,8 @@ import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
import org.whispersystems.textsecuregcm.auth.ChangesLinkedDevices;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
import org.whispersystems.textsecuregcm.entities.DeviceAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
import org.whispersystems.textsecuregcm.entities.DeviceInfoList;
import org.whispersystems.textsecuregcm.entities.LinkDeviceRequest;
@@ -93,7 +93,6 @@ public class DeviceController {
private final AccountsManager accounts;
private final RateLimiters rateLimiters;
private final PersistentTimer persistentTimer;
private final Map<String, Integer> maxDeviceConfiguration;
private final EnumMap<ClientPlatform, AtomicInteger> linkedDeviceListenersByPlatform;
private final AtomicInteger linkedDeviceListenersForUnrecognizedPlatforms;
@@ -117,13 +116,11 @@ public class DeviceController {
public DeviceController(final AccountsManager accounts,
final RateLimiters rateLimiters,
final PersistentTimer persistentTimer,
final Map<String, Integer> maxDeviceConfiguration) {
final PersistentTimer persistentTimer) {
this.accounts = accounts;
this.rateLimiters = rateLimiters;
this.persistentTimer = persistentTimer;
this.maxDeviceConfiguration = maxDeviceConfiguration;
linkedDeviceListenersByPlatform =
EnumMapUtil.toEnumMap(ClientPlatform.class, clientPlatform -> buildGauge(clientPlatform.name().toLowerCase()));
@@ -204,14 +201,8 @@ public class DeviceController {
rateLimiters.getAllocateDeviceLimiter().validate(account.getUuid());
int maxDeviceLimit = MAX_DEVICES;
if (maxDeviceConfiguration.containsKey(account.getNumber())) {
maxDeviceLimit = maxDeviceConfiguration.get(account.getNumber());
}
if (account.getDevices().size() >= maxDeviceLimit) {
throw new DeviceLimitExceededException(account.getDevices().size(), maxDeviceLimit);
if (account.getDevices().size() >= MAX_DEVICES) {
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
}
if (auth.deviceId() != Device.PRIMARY_ID) {
@@ -250,7 +241,7 @@ public class DeviceController {
.orElseThrow(ForbiddenException::new);
final DeviceActivationRequest deviceActivationRequest = linkDeviceRequest.deviceActivationRequest();
final AccountAttributes accountAttributes = linkDeviceRequest.accountAttributes();
final DeviceAttributes deviceAttributes = linkDeviceRequest.deviceAttributes();
rateLimiters.getVerifyDeviceLimiter().validate(account.getUuid());
@@ -268,13 +259,11 @@ public class DeviceController {
throw new WebApplicationException(Response.status(422).build());
}
final int maxDeviceLimit = maxDeviceConfiguration.getOrDefault(account.getNumber(), MAX_DEVICES);
if (account.getDevices().size() >= maxDeviceLimit) {
throw new DeviceLimitExceededException(account.getDevices().size(), maxDeviceLimit);
if (account.getDevices().size() >= MAX_DEVICES) {
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
}
final Set<DeviceCapability> capabilities = accountAttributes.getCapabilities();
final Set<DeviceCapability> capabilities = deviceAttributes.capabilities();
if (capabilities == null) {
throw new WebApplicationException(Response.status(422, "Missing device capabilities").build());
@@ -293,13 +282,13 @@ public class DeviceController {
}
try {
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account, new DeviceSpec(accountAttributes.getName(),
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account, new DeviceSpec(deviceAttributes.name(),
authorizationHeader.getPassword(),
signalAgent,
capabilities,
accountAttributes.getRegistrationId(),
accountAttributes.getPhoneNumberIdentityRegistrationId(),
accountAttributes.getFetchesMessages(),
deviceAttributes.registrationId(),
deviceAttributes.phoneNumberIdentityRegistrationId(),
deviceAttributes.fetchesMessages(),
deviceActivationRequest.apnToken(),
deviceActivationRequest.gcmToken(),
deviceActivationRequest.aciSignedPreKey(),
@@ -53,6 +53,7 @@ import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ServiceId;
@@ -79,6 +80,7 @@ import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialProfileResponse;
import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes;
import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
@@ -94,6 +96,7 @@ import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
@@ -122,6 +125,7 @@ public class ProfileController {
private static final String VERSION_NOT_FOUND_COUNTER_NAME = name(ProfileController.class, "versionNotFound");
private static final String DUPLICATE_AUTHENTICATION_COUNTER_NAME = name(ProfileController.class, "duplicateAuthentication");
private static final String BATCH_IDENTITY_CHECK_RATE_LIMITED_COUNTER_NAME = name(ProfileController.class, "batchIdentityCheckRateLimited");
public ProfileController(
Clock clock,
@@ -372,7 +376,20 @@ public class ProfileController {
description = "Batch check completed successfully. Response may contain accounts with mismatched fingerprints.",
content = @Content(schema = @Schema(implementation = BatchIdentityCheckResponse.class)))
@ApiResponse(responseCode = "400", description = "Invalid request format or validation failed.")
public CompletableFuture<BatchIdentityCheckResponse> runBatchIdentityCheck(@NotNull @Valid BatchIdentityCheckRequest request) {
public CompletableFuture<BatchIdentityCheckResponse> runBatchIdentityCheck(
@NotNull @Valid final BatchIdentityCheckRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@Context final ContainerRequestContext containerRequestContext) {
final String remoteAddress = (String) containerRequestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
if (StringUtils.isNotBlank(remoteAddress)) {
rateLimiters.getBatchIdentityCheckLimiter().validateAsync(remoteAddress)
.whenComplete((_, t) -> {
if (t != null && ExceptionUtils.unwrap(t) instanceof RateLimitExceededException) {
Metrics.counter(BATCH_IDENTITY_CHECK_RATE_LIMITED_COUNTER_NAME,
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).increment();
}
});
}
return CompletableFuture.supplyAsync(() -> {
List<BatchIdentityCheckResponse.Element> responseElements = Collections.synchronizedList(new ArrayList<>());
@@ -136,7 +136,14 @@ public class RegistrationController {
final PhoneVerificationRequest.VerificationType verificationType =
phoneVerificationTokenManager.verify(requestContext, number, registrationRequest);
final Optional<Account> existingAccount = accounts.getByE164(number);
// 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)
.stream()
.map(accounts::getByE164)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
existingAccount.ifPresent(account -> {
final Instant accountLastSeen = Instant.ofEpochMilli(account.getLastSeen());
@@ -77,6 +77,7 @@ import org.whispersystems.textsecuregcm.entities.VerificationSessionResponse;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.CaptchaMetrics;
import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.PushNotification;
@@ -492,6 +493,11 @@ public class VerificationController {
Tag.of(SCORE_TAG_NAME, assessmentResult.getScoreString())))
.increment();
CaptchaMetrics.measureCaptchaOutcome(assessmentResult.getNormalizedIntScore(),
assessmentResult.isValid(captchaScoreThreshold),
Util.getRegion(registrationServiceSession.number()),
"verification");
} catch (final IOException e) {
logger.error("error assessing captcha during registration verification", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, e);
@@ -4,40 +4,30 @@
*/
package org.whispersystems.textsecuregcm.entities;
import static org.whispersystems.textsecuregcm.util.RegistrationIdValidator.validRegistrationId;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Size;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter;
import org.whispersystems.textsecuregcm.util.ExactlySize;
public class AccountAttributes {
@JsonProperty
private boolean fetchesMessages;
private static final String UAK_VALIDATION_COUNTER_NAME = MetricsUtil.name(AccountAttributes.class, "uakValidation");
@JsonProperty
private int registrationId;
@JsonProperty("pniRegistrationId")
private int phoneNumberIdentityRegistrationId;
@JsonProperty
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Size(max = 225)
private byte[] name;
@JsonUnwrapped
@Valid
private DeviceAttributes deviceAttributes;
@JsonProperty
@ExactlySize({0, 64})
@@ -50,12 +40,6 @@ public class AccountAttributes {
@JsonProperty
private boolean unrestrictedUnidentifiedAccess;
@JsonProperty
@JsonSerialize(using = DeviceCapabilityAdapter.Serializer.class)
@JsonDeserialize(using = DeviceCapabilityAdapter.Deserializer.class)
@Nullable
private Set<DeviceCapability> capabilities;
@JsonProperty
private boolean discoverableByPhoneNumber = true;
@@ -77,29 +61,26 @@ public class AccountAttributes {
final String registrationLock,
final boolean discoverableByPhoneNumber,
final Set<DeviceCapability> capabilities) {
this.fetchesMessages = fetchesMessages;
this.registrationId = registrationId;
this.phoneNumberIdentityRegistrationId = phoneNumberIdentifierRegistrationId;
this.name = name;
this.deviceAttributes = new DeviceAttributes(fetchesMessages, registrationId, phoneNumberIdentifierRegistrationId, name, capabilities);
this.registrationLock = registrationLock;
this.discoverableByPhoneNumber = discoverableByPhoneNumber;
this.capabilities = capabilities;
}
public boolean getFetchesMessages() {
return fetchesMessages;
return deviceAttributes.fetchesMessages();
}
public int getRegistrationId() {
return registrationId;
return deviceAttributes.registrationId();
}
public int getPhoneNumberIdentityRegistrationId() {
return phoneNumberIdentityRegistrationId;
return deviceAttributes.phoneNumberIdentityRegistrationId();
}
public byte[] getName() {
return name;
return deviceAttributes.name();
}
public String getRegistrationLock() {
@@ -116,7 +97,7 @@ public class AccountAttributes {
@Nullable
public Set<DeviceCapability> getCapabilities() {
return capabilities;
return deviceAttributes.capabilities();
}
public boolean isDiscoverableByPhoneNumber() {
@@ -128,20 +109,46 @@ public class AccountAttributes {
}
@VisibleForTesting
public AccountAttributes withUnidentifiedAccessKey(final byte[] unidentifiedAccessKey) {
public AccountAttributes setUnidentifiedAccessKey(final byte[] unidentifiedAccessKey) {
this.unidentifiedAccessKey = unidentifiedAccessKey;
return this;
}
@VisibleForTesting
public AccountAttributes withRecoveryPassword(final byte[] recoveryPassword) {
public AccountAttributes setRecoveryPassword(final byte[] recoveryPassword) {
this.recoveryPassword = recoveryPassword;
return this;
}
@VisibleForTesting
public AccountAttributes setDeviceAttributes(final DeviceAttributes deviceAttributes) {
this.deviceAttributes = deviceAttributes;
return this;
}
@VisibleForTesting
public AccountAttributes setUnrestrictedUnidentifiedAccess(final boolean unrestrictedUnidentifiedAccess) {
this.unrestrictedUnidentifiedAccess = unrestrictedUnidentifiedAccess;
return this;
}
@VisibleForTesting
public static final boolean ENFORCE_VALID_UNRESTRICTED_UAK = false;
@AssertTrue
@Schema(hidden = true)
public boolean isEachRegistrationIdValid() {
return validRegistrationId(registrationId) && validRegistrationId(phoneNumberIdentityRegistrationId);
public boolean isUnrestrictedUakValid() {
final boolean valid = unrestrictedUnidentifiedAccess ||
(!unrestrictedUnidentifiedAccess && (unidentifiedAccessKey != null
&& unidentifiedAccessKey.length == 16));
Metrics.counter(UAK_VALIDATION_COUNTER_NAME,
"valid", String.valueOf(valid),
"unrestricted", String.valueOf(unrestrictedUnidentifiedAccess)
).increment();
// initially, only gather metrics
return true;
}
}
@@ -0,0 +1,46 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import static org.whispersystems.textsecuregcm.util.RegistrationIdValidator.validRegistrationId;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Size;
import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter;
public record DeviceAttributes(
boolean fetchesMessages,
int registrationId,
@JsonProperty("pniRegistrationId") int phoneNumberIdentityRegistrationId,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Size(max = 225)
byte[] name,
@JsonSerialize(using = DeviceCapabilityAdapter.Serializer.class)
@JsonDeserialize(using = DeviceCapabilityAdapter.Deserializer.class)
@Nullable
Set<DeviceCapability> capabilities) {
@AssertTrue
@Schema(hidden = true)
public boolean isEachRegistrationIdValid() {
return validRegistrationId(registrationId) && validRegistrationId(phoneNumberIdentityRegistrationId);
}
}
@@ -14,6 +14,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
import java.util.List;
@@ -21,6 +22,7 @@ import java.util.Objects;
import org.whispersystems.textsecuregcm.controllers.MessageController;
public record IncomingMessageList(@NotNull
@NotEmpty
@Valid
List<@NotNull @Valid IncomingMessage> messages,
@@ -19,7 +19,8 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
@NotNull
@Valid
AccountAttributes accountAttributes,
@JsonProperty("accountAttributes")
DeviceAttributes deviceAttributes,
@NotNull
@Valid
@@ -30,7 +31,7 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
@JsonCreator
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public LinkDeviceRequest(@JsonProperty("verificationCode") String verificationCode,
@JsonProperty("accountAttributes") AccountAttributes accountAttributes,
@JsonProperty("accountAttributes") DeviceAttributes deviceAttributes,
@JsonProperty("aciSignedPreKey") @NotNull @Valid ECSignedPreKey aciSignedPreKey,
@JsonProperty("pniSignedPreKey") @NotNull @Valid ECSignedPreKey pniSignedPreKey,
@JsonProperty("aciPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey aciPqLastResortPreKey,
@@ -38,14 +39,14 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
@JsonProperty("apnToken") Optional<@Valid ApnRegistrationId> apnToken,
@JsonProperty("gcmToken") Optional<@Valid GcmRegistrationId> gcmToken) {
this(verificationCode, accountAttributes,
this(verificationCode, deviceAttributes,
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, apnToken, gcmToken));
}
@AssertTrue
@Schema(hidden = true)
public boolean isExactlyOneMessageDeliveryChannel() {
if (accountAttributes != null && accountAttributes.getFetchesMessages()) {
if (deviceAttributes != null && deviceAttributes.fetchesMessages()) {
return deviceActivationRequest().apnToken().isEmpty() && deviceActivationRequest().gcmToken().isEmpty();
} else {
return deviceActivationRequest().apnToken().isPresent() ^ deviceActivationRequest().gcmToken().isPresent();
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.UUID;
@@ -34,6 +35,8 @@ import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
import org.signal.chat.account.SetRegistrationRecoveryPasswordResponse;
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.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
@@ -267,6 +270,24 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
return SetRegistrationRecoveryPasswordResponse.getDefaultInstance();
}
@Override
public SetZkCredentialKeyResponse setZkCredentialKey(final SetZkCredentialKeyRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account authenticatedAccount = getAuthenticatedAccount();
final byte[] zkCredentialKey = request.getPublicKey().toByteArray();
if (Arrays.equals(authenticatedAccount.getZkCredentialKey(), zkCredentialKey)) {
return SetZkCredentialKeyResponse.getDefaultInstance();
}
rateLimiters.getSetZkCredentialKeyLimiter().validate(authenticatedDevice.accountIdentifier());
accountsManager.update(authenticatedAccount, account -> account.setZkCredentialKey(zkCredentialKey));
return SetZkCredentialKeyResponse.getDefaultInstance();
}
private Account getAuthenticatedAccount() {
return getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedDevice());
}
@@ -14,8 +14,10 @@ import java.io.IOException;
import java.util.List;
import java.util.Optional;
import org.whispersystems.textsecuregcm.captcha.Action;
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.metrics.CaptchaMetrics;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.spam.ChallengeType;
@@ -61,13 +63,18 @@ public class RateLimitChallengeManager {
}
}
public boolean answerCaptchaChallenge(final Account account, final String captcha, final String mostRecentProxyIp,
final String userAgent, final Optional<Float> scoreThreshold)
throws RateLimitExceededException, IOException {
public boolean answerCaptchaChallenge(final Account account,
final String captcha,
final String mostRecentProxyIp,
final String userAgent,
final Optional<Float> scoreThreshold) throws RateLimitExceededException, IOException {
rateLimiters.getCaptchaChallengeAttemptLimiter().validate(account.getUuid());
final boolean challengeSuccess = captchaChecker.verify(Optional.of(account.getUuid()), Action.CHALLENGE, captcha, mostRecentProxyIp, userAgent).isValid(scoreThreshold);
final AssessmentResult assessmentResult =
captchaChecker.verify(Optional.of(account.getUuid()), Action.CHALLENGE, captcha, mostRecentProxyIp, userAgent);
final boolean challengeSuccess = assessmentResult.isValid(scoreThreshold);
final Tags tags = Tags.of(
Tag.of(SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account.getNumber())),
@@ -77,6 +84,13 @@ public class RateLimitChallengeManager {
Metrics.counter(CAPTCHA_ATTEMPT_COUNTER_NAME, tags).increment();
CaptchaMetrics.measureCaptchaOutcome(assessmentResult.getNormalizedIntScore(),
challengeSuccess,
Util.getRegion(account.getNumber()),
// Note: currently all challenges are for message-sending, but if we add more use cases, we'll need to make the
// accept a context from callers rather than hard-coding it here
"sendMessage");
if (challengeSuccess) {
rateLimiters.getCaptchaChallengeSuccessLimiter().validate(account.getUuid());
resetRateLimits(account, ChallengeType.CAPTCHA);
@@ -36,6 +36,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
USERNAME_LINK_LOOKUP_PER_IP("usernameLinkLookupPerIp", new RateLimiterConfig(100, Duration.ofSeconds(15), true)),
CHECK_ACCOUNT_EXISTENCE("checkAccountExistence", new RateLimiterConfig(1000, Duration.ofSeconds(4), true)),
REGISTRATION("registration", new RateLimiterConfig(6, Duration.ofSeconds(30), false)),
SET_ZK_CREDENTIAL_KEY("setZkCredentialKey", new RateLimiterConfig(5, Duration.ofDays(7), false)),
VERIFICATION_PUSH_CHALLENGE("verificationPushChallenge", new RateLimiterConfig(5, Duration.ofSeconds(30), false)),
VERIFICATION_CAPTCHA("verificationCaptcha", new RateLimiterConfig(10, Duration.ofSeconds(30), false)),
RATE_LIMIT_RESET("rateLimitReset", new RateLimiterConfig(2, Duration.ofHours(12), false)),
@@ -58,7 +59,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
RECORD_DEVICE_TRANSFER_REQUEST("recordDeviceTransferRequest", new RateLimiterConfig(10, Duration.ofMillis(100), true)),
WAIT_FOR_DEVICE_TRANSFER_REQUEST("waitForDeviceTransferRequest", new RateLimiterConfig(10, Duration.ofMillis(100), true)),
DEVICE_CHECK_CHALLENGE("deviceCheckChallenge", new RateLimiterConfig(10, Duration.ofMinutes(1), false)),
SUBMIT_CALL_QUALITY_SURVEY("submitCallQualitySurvey", new RateLimiterConfig(100, Duration.ofMinutes(1), true))
SUBMIT_CALL_QUALITY_SURVEY("submitCallQualitySurvey", new RateLimiterConfig(100, Duration.ofMinutes(1), true)),
BATCH_IDENTITY_CHECK("batchIdentityCheck", new RateLimiterConfig(100, Duration.ofMinutes(1), true)),
;
private final String id;
@@ -105,8 +107,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.VERIFY_DEVICE);
}
public RateLimiter getMessagesLimiter() {
return forDescriptor(For.MESSAGES);
public RateLimiter getSetZkCredentialKeyLimiter() {
return forDescriptor(For.SET_ZK_CREDENTIAL_KEY);
}
public RateLimiter getPreKeysLimiter() {
@@ -161,6 +163,10 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.REGISTRATION);
}
public RateLimiter getMessagesLimiter() {
return forDescriptor(For.MESSAGES);
}
public RateLimiter getRateLimitResetLimiter() {
return forDescriptor(For.RATE_LIMIT_RESET);
}
@@ -232,4 +238,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
public RateLimiter getSubmitCallQualitySurveyLimiter() {
return forDescriptor(For.SUBMIT_CALL_QUALITY_SURVEY);
}
public RateLimiter getBatchIdentityCheckLimiter() {
return forDescriptor(For.BATCH_IDENTITY_CHECK);
}
}
@@ -0,0 +1,31 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.metrics;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
public class CaptchaMetrics {
private static final String CAPTCHA_OUTCOME_DISTRIBUTION_NAME = MetricsUtil.name(CaptchaMetrics.class, "outcome");
private CaptchaMetrics() {}
public static void measureCaptchaOutcome(final int score,
final boolean success,
final String region,
final String context) {
DistributionSummary.builder(CAPTCHA_OUTCOME_DISTRIBUTION_NAME)
.tags("success", String.valueOf(success),
"regionCode", region,
"context", context)
.minimumExpectedValue(1.0d)
.maximumExpectedValue(100.0d)
.register(Metrics.globalRegistry)
.record(Math.max(1, score));
}
}
@@ -304,8 +304,11 @@ public class MessageSender {
}
if (messagesByDeviceId.isEmpty()) {
if (syncMessageSenderDeviceId.isEmpty()) {
throw new IllegalArgumentException("Messages must not be empty for non-sync messages");
}
Metrics.counter(EMPTY_MESSAGE_LIST_COUNTER_NAME,
Tags.of(SYNC_MESSAGE_TAG_NAME, String.valueOf(syncMessageSenderDeviceId.isPresent())).and(platformTag)).increment();
Tags.of(SYNC_MESSAGE_TAG_NAME, String.valueOf(true)).and(platformTag)).increment();
}
final byte excludedDeviceId;
@@ -92,6 +92,7 @@ public class Account {
private String registrationLockSalt;
@JsonProperty("uak")
@Nullable
private byte[] unidentifiedAccessKey;
@JsonProperty("uua")
@@ -112,6 +113,10 @@ public class Account {
@Nullable
private BackupVoucher backupVoucher;
@JsonProperty("zck")
@Nullable
private byte[] zkCredentialKey;
@JsonProperty
private int version;
@@ -428,7 +433,9 @@ public class Account {
public Optional<byte[]> getUnidentifiedAccessKey() {
requireNotStale();
return Optional.ofNullable(unidentifiedAccessKey);
return Optional.ofNullable((unidentifiedAccessKey == null || unidentifiedAccessKey.length == 0)
? null
: unidentifiedAccessKey);
}
public void setUnidentifiedAccessKey(final byte[] unidentifiedAccessKey) {
@@ -536,6 +543,15 @@ public class Account {
this.usernameHolds = usernameHolds;
}
@Nullable
public byte[] getZkCredentialKey() {
return zkCredentialKey;
}
public void setZkCredentialKey(@Nullable final byte[] zkCredentialKey) {
this.zkCredentialKey = zkCredentialKey;
}
public void markStale() {
stale = true;
}
@@ -326,6 +326,9 @@ public class Accounts {
// Carry over the existing backup voucher to the new account
accountToCreate.setBackupVoucher(existingAccount.getBackupVoucher());
// Carry over the existing ZK credential key to the new account
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey());
final List<TransactWriteItem> writeItems = new ArrayList<>();
// If we're reclaiming an account that already has a username, we'd like to give the re-registering client
@@ -1234,6 +1237,18 @@ public class Accounts {
.build();
}
private TransactWriteItem buildConditionalDeleteAccount(final Account account) {
return TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(accountsTableName)
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())))
.conditionExpression("#version = :version")
.expressionAttributeNames(Map.of("#version", ATTR_VERSION))
.expressionAttributeValues(Map.of(":version", AttributeValues.fromInt(account.getVersion())))
.build())
.build();
}
@Nonnull
public CompletableFuture<Optional<Account>> getByAccountIdentifierAsync(final UUID uuid) {
return AsyncTimerUtil.record(GET_BY_UUID_TIMER, () -> itemByKeyAsync(accountsTableName, KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid))
@@ -1274,34 +1289,51 @@ public class Accounts {
public void delete(final UUID uuid, final List<TransactWriteItem> additionalWriteItems) {
final Timer.Sample sample = Timer.start();
int tries = 0;
final int maxTries = 3;
try {
final Account account;
{
final Optional<Account> maybeAccount = getByAccountIdentifier(uuid);
while (tries < maxTries) {
try {
final Account account;
{
final Optional<Account> maybeAccount = getByAccountIdentifier(uuid);
if (maybeAccount.isEmpty()) {
if (maybeAccount.isEmpty()) {
return;
}
account = maybeAccount.get();
}
final List<TransactWriteItem> transactWriteItems = new ArrayList<>(List.of(
buildConditionalDeleteAccount(account),
buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, account.getNumber()),
buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, account.getPhoneNumberIdentifier()),
buildPutDeletedAccount(uuid, account.getPhoneNumberIdentifier())
));
account.getUsernameHash().ifPresent(usernameHash -> transactWriteItems.add(
buildDelete(usernamesConstraintTableName, UsernameTable.KEY_USERNAME_HASH, usernameHash)));
transactWriteItems.addAll(additionalWriteItems);
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(transactWriteItems)
.build());
return;
} catch (final TransactionCanceledException e) {
final CancellationReason cancellationReason = e.cancellationReasons().get(0);
if (conditionalCheckFailed(cancellationReason) || isTransactionConflict(cancellationReason)) {
// This means that either the optimistic delete failed because something else changed the account from under us,
// or there is an ongoing transaction for the account item. Either way, retry until the max attempts.
tries++;
} else {
throw new RuntimeException("Account deletion transaction canceled", e);
}
}
account = maybeAccount.get();
}
final List<TransactWriteItem> transactWriteItems = new ArrayList<>(List.of(
buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, account.getNumber()),
buildDelete(accountsTableName, KEY_ACCOUNT_UUID, uuid),
buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, account.getPhoneNumberIdentifier()),
buildPutDeletedAccount(uuid, account.getPhoneNumberIdentifier())
));
account.getUsernameHash().ifPresent(usernameHash -> transactWriteItems.add(
buildDelete(usernamesConstraintTableName, UsernameTable.KEY_USERNAME_HASH, usernameHash)));
transactWriteItems.addAll(additionalWriteItems);
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(transactWriteItems)
.build());
throw new OptimisticLockRetryLimitExceededException();
} finally {
sample.stop(DELETE_TIMER);
}
@@ -11,7 +11,6 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import io.dropwizard.lifecycle.Managed;
import io.lettuce.core.RedisCommandTimeoutException;
import io.lettuce.core.RedisException;
@@ -64,7 +63,6 @@ import org.signal.libsignal.protocol.IdentityKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
@@ -957,11 +955,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
});
}
public Account updateDeviceAuthentication(final Account account, final Device device, final SaltedTokenHash credentials) {
Preconditions.checkArgument(credentials.getVersion() == SaltedTokenHash.CURRENT_VERSION);
return updateDevice(account, device.getId(), device1 -> device1.setAuthTokenHash(credentials));
}
/**
* @param account account to update
* @param updater must return {@code true} if the account was actually updated
@@ -57,6 +57,9 @@ service Accounts {
// Sets the registration recovery password for the authenticated account.
rpc SetRegistrationRecoveryPassword(SetRegistrationRecoveryPasswordRequest) returns (SetRegistrationRecoveryPasswordResponse) {}
// Store a public key used to issue and verify zero-knowledge (anonymous) credentials for the account.
rpc SetZkCredentialKey(SetZkCredentialKeyRequest) returns (SetZkCredentialKeyResponse) {}
}
// Provides methods for looking up Signal accounts. Callers must not provide
@@ -194,7 +197,7 @@ message ConfigureUnidentifiedAccessRequest {
// anonymously (i.e. to retrieve keys or profiles or to send messages) unless
// unrestricted unidentified access is permitted. Must be present if
// unrestricted unidentified access is not allowed.
bytes unidentified_access_key = 1;
bytes unidentified_access_key = 1 [(require.exactlySize) = 0, (require.exactlySize) = 16];
// If `true`, any user may interact with this account anonymously without
// providing an unidentified access key. Otherwise, users must provide the
@@ -265,3 +268,11 @@ message LookupUsernameLinkResponse {
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
}
}
message SetZkCredentialKeyRequest {
// A serialized Ristretto key with a one-byte type prefix
bytes public_key = 1 [(require.exactlySize) = 33];
}
message SetZkCredentialKeyResponse {
}
@@ -14,7 +14,6 @@ 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.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -167,7 +166,6 @@ class AccountAuthenticatorTest {
when(device.getId()).thenReturn(deviceId);
when(device.getAuthTokenHash()).thenReturn(credentials);
when(credentials.verify(password)).thenReturn(true);
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
final Optional<AuthenticatedDevice> maybeAuthenticatedAccount =
accountAuthenticator.authenticate(new BasicCredentials(uuid.toString(), password));
@@ -175,7 +173,6 @@ class AccountAuthenticatorTest {
assertThat(maybeAuthenticatedAccount).isPresent();
assertThat(maybeAuthenticatedAccount.orElseThrow().accountIdentifier()).isEqualTo(uuid);
assertThat(maybeAuthenticatedAccount.orElseThrow().deviceId()).isEqualTo(device.getId());
verify(accountsManager, never()).updateDeviceAuthentication(any(), any(), any());
}
@Test
@@ -197,7 +194,6 @@ class AccountAuthenticatorTest {
when(device.getId()).thenReturn(deviceId);
when(device.getAuthTokenHash()).thenReturn(credentials);
when(credentials.verify(password)).thenReturn(true);
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
final Optional<AuthenticatedDevice> maybeAuthenticatedAccount =
accountAuthenticator.authenticate(new BasicCredentials(uuid + "." + deviceId, password));
@@ -205,7 +201,6 @@ class AccountAuthenticatorTest {
assertThat(maybeAuthenticatedAccount).isPresent();
assertThat(maybeAuthenticatedAccount.orElseThrow().accountIdentifier()).isEqualTo(uuid);
assertThat(maybeAuthenticatedAccount.orElseThrow().deviceId()).isEqualTo(device.getId());
verify(accountsManager, never()).updateDeviceAuthentication(any(), any(), any());
}
@CartesianTest
@@ -228,7 +223,6 @@ class AccountAuthenticatorTest {
when(authenticatedDevice.getId()).thenReturn(deviceId);
when(authenticatedDevice.getAuthTokenHash()).thenReturn(credentials);
when(credentials.verify(password)).thenReturn(true);
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
final String identifier;
if (authenticatedDeviceIsPrimary) {
@@ -244,37 +238,6 @@ class AccountAuthenticatorTest {
assertThat(maybeAuthenticatedAccount.orElseThrow().deviceId()).isEqualTo(authenticatedDevice.getId());
}
@Test
void testAuthenticateV1() {
final UUID uuid = UUID.randomUUID();
final byte deviceId = 1;
final String password = "12345";
final Account account = mock(Account.class);
final Device device = mock(Device.class);
final SaltedTokenHash credentials = mock(SaltedTokenHash.class);
clock.unpin();
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
when(account.getUuid()).thenReturn(uuid);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(uuid);
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
when(account.getPrimaryDevice()).thenReturn(device);
when(device.getId()).thenReturn(deviceId);
when(device.getAuthTokenHash()).thenReturn(credentials);
when(credentials.verify(password)).thenReturn(true);
when(credentials.getVersion()).thenReturn(SaltedTokenHash.Version.V1);
final Optional<AuthenticatedDevice> maybeAuthenticatedAccount =
accountAuthenticator.authenticate(new BasicCredentials(uuid.toString(), password));
assertThat(maybeAuthenticatedAccount).isPresent();
assertThat(maybeAuthenticatedAccount.orElseThrow().accountIdentifier()).isEqualTo(uuid);
assertThat(maybeAuthenticatedAccount.orElseThrow().deviceId()).isEqualTo(device.getId());
verify(accountsManager, times(1)).updateDeviceAuthentication(
any(), // this won't be 'account', because it'll already be updated by updateDeviceLastSeen
eq(device), any());
}
@Test
void testAuthenticateAccountNotFound() {
assertThat(accountAuthenticator.authenticate(new BasicCredentials(UUID.randomUUID().toString(), "password")))
@@ -300,7 +263,6 @@ class AccountAuthenticatorTest {
when(device.getId()).thenReturn(deviceId);
when(device.getAuthTokenHash()).thenReturn(credentials);
when(credentials.verify(password)).thenReturn(true);
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
final Optional<AuthenticatedDevice> maybeAuthenticatedAccount =
accountAuthenticator.authenticate(new BasicCredentials(uuid + "." + (deviceId + 1), password));
@@ -328,7 +290,6 @@ class AccountAuthenticatorTest {
when(device.getId()).thenReturn(deviceId);
when(device.getAuthTokenHash()).thenReturn(credentials);
when(credentials.verify(password)).thenReturn(true);
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
final String incorrectPassword = password + "incorrect";
@@ -13,6 +13,7 @@ import static org.mockito.Mockito.when;
import jakarta.ws.rs.WebApplicationException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
@@ -28,6 +29,7 @@ import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class OptionalAccessTest {
@@ -51,20 +53,23 @@ class OptionalAccessTest {
}
private static List<Arguments> verify() {
final String unidentifiedAccessKey = RandomStringUtils.secure().nextAlphanumeric(16);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(16);
final Anonymous correctUakHeader =
new Anonymous(Base64.getEncoder().encodeToString(unidentifiedAccessKey.getBytes()));
new Anonymous(Base64.getEncoder().encodeToString(unidentifiedAccessKey));
final byte[] incorrectUnidentifiedAccessKey = Arrays.copyOf(unidentifiedAccessKey, unidentifiedAccessKey.length);
incorrectUnidentifiedAccessKey[0] = (byte)(incorrectUnidentifiedAccessKey[0]+1);
final Anonymous incorrectUakHeader =
new Anonymous(Base64.getEncoder().encodeToString((unidentifiedAccessKey + "-incorrect").getBytes()));
new Anonymous(Base64.getEncoder().encodeToString(incorrectUnidentifiedAccessKey));
final Account targetAccount = mock(Account.class);
final ServiceIdentifier targetAccountAciIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final ServiceIdentifier targetAccountPniIdentifier = new PniServiceIdentifier(UUID.randomUUID());
when(targetAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(mock(Device.class)));
when(targetAccount.getUnidentifiedAccessKey())
.thenReturn(Optional.of(unidentifiedAccessKey.getBytes(StandardCharsets.UTF_8)));
.thenReturn(Optional.of(unidentifiedAccessKey));
when(targetAccount.isIdentifiedBy(targetAccountAciIdentifier)).thenReturn(true);
when(targetAccount.isIdentifiedBy(targetAccountPniIdentifier)).thenReturn(true);
@@ -84,7 +89,7 @@ class OptionalAccessTest {
final ServiceIdentifier inactiveTargetAccountAciIdentifier = new AciServiceIdentifier(UUID.randomUUID());
when(inactiveTargetAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(mock(Device.class)));
when(inactiveTargetAccount.getUnidentifiedAccessKey())
.thenReturn(Optional.of(unidentifiedAccessKey.getBytes(StandardCharsets.UTF_8)));
.thenReturn(Optional.of(unidentifiedAccessKey));
when(inactiveTargetAccount.isIdentifiedBy(inactiveTargetAccountAciIdentifier)).thenReturn(true);
return List.of(
@@ -36,6 +36,7 @@ import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
@@ -47,6 +48,7 @@ import java.util.stream.Stream;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -776,13 +778,43 @@ class AccountControllerTest {
}
}
@ParameterizedTest
@MethodSource
void testSetAccountAttributesUnrestrictedUnidentifiedAccess(final boolean unrestrictedUnidentifiedAccess, final byte[] unidentifiedAccessKey, final int expectedStatus) {
// This test is only valid when validations are enforced
Assumptions.assumeTrue(AccountAttributes.ENFORCE_VALID_UNRESTRICTED_UAK);
try (final Response response = resources.getJerseyTest()
.target("/v1/accounts/attributes/")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null)
.setUnidentifiedAccessKey(unidentifiedAccessKey)
.setUnrestrictedUnidentifiedAccess(unrestrictedUnidentifiedAccess)))) {
assertThat(response.getStatus()).isEqualTo(expectedStatus);
}
}
static Collection<Arguments> testSetAccountAttributesUnrestrictedUnidentifiedAccess() {
return List.of(
Arguments.argumentSet("restricted, non-empty UAK", false, new byte[16], 204),
Arguments.argumentSet("unrestricted, empty UAK", true, new byte[0], 204),
Arguments.argumentSet("restricted, empty UAK", false, new byte[0], 422),
Arguments.argumentSet("unrestricted, non-empty UAK", true, new byte[16], 204)
);
}
@Test
void testSetAccountAttributesNoDiscoverabilityChange() {
try (final Response response = resources.getJerseyTest()
.target("/v1/accounts/attributes/")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null)))) {
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null)
.setUnidentifiedAccessKey(new byte[16])))) {
assertThat(response.getStatus()).isEqualTo(204);
}
@@ -794,7 +826,8 @@ class AccountControllerTest {
.target("/v1/accounts/attributes/")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.UNDISCOVERABLE_UUID, AuthHelper.UNDISCOVERABLE_PASSWORD))
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null)))) {
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null)
.setUnidentifiedAccessKey(new byte[16])))) {
assertThat(response.getStatus()).isEqualTo(204);
}
@@ -811,7 +844,8 @@ class AccountControllerTest {
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.UNDISCOVERABLE_UUID, AuthHelper.UNDISCOVERABLE_PASSWORD))
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null)
.withRecoveryPassword(recoveryPassword)))) {
.setUnidentifiedAccessKey(new byte[16])
.setRecoveryPassword(recoveryPassword)))) {
assertThat(response.getStatus()).isEqualTo(204);
verify(registrationRecoveryPasswordsManager).store(AuthHelper.UNDISCOVERABLE_PNI, recoveryPassword);
@@ -824,7 +858,8 @@ class AccountControllerTest {
.target("/v1/accounts/attributes/")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, false, null)))) {
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, false, null)
.setUnidentifiedAccessKey(new byte[16])))) {
assertThat(response.getStatus()).isEqualTo(204);
}
@@ -837,7 +872,7 @@ class AccountControllerTest {
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, false, null)
.withUnidentifiedAccessKey(new byte[7])))) {
.setUnidentifiedAccessKey(new byte[7])))) {
assertThat(response.getStatus()).isEqualTo(422);
}
@@ -22,6 +22,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.List;
@@ -46,6 +47,7 @@ import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
import org.whispersystems.textsecuregcm.entities.MessageProtos.SenderCertificate;
@@ -214,7 +216,9 @@ class CertificateControllerTest {
Response response = resources.getJerseyTest()
.target("/v1/certificate/delivery")
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("1234".getBytes()))
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY,
AuthHelper.getUnidentifiedAccessHeader(
Arrays.copyOf("1234".getBytes(), UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH)))
.get();
assertEquals(401, response.getStatus());
@@ -35,9 +35,7 @@ import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Base64;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
@@ -62,9 +60,9 @@ import org.mockito.ArgumentCaptor;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
import org.whispersystems.textsecuregcm.entities.DeviceAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
import org.whispersystems.textsecuregcm.entities.DeviceInfoList;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
@@ -111,7 +109,6 @@ class DeviceControllerTest {
private static final Account account = mock(Account.class);
private static final Account maxedAccount = mock(Account.class);
private static final Device primaryDevice = mock(Device.class);
private static final Map<String, Integer> deviceConfiguration = new HashMap<>();
private static final TestClock testClock = TestClock.now();
private static final byte NEXT_DEVICE_ID = 42;
@@ -119,8 +116,7 @@ class DeviceControllerTest {
private static final DeviceController deviceController = new DeviceController(
accountsManager,
rateLimiters,
persistentTimer,
deviceConfiguration);
persistentTimer);
private static final ResourceExtension resources = ResourceExtension.builder()
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
@@ -256,11 +252,11 @@ class DeviceControllerTest {
when(asyncCommands.set(any(), any(), any())).thenReturn(MockRedisFuture.completedFuture(null));
final AccountAttributes accountAttributes = new AccountAttributes(fetchesMessages, 1234, 5678, null,
null, true, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
final DeviceAttributes deviceAttributes = new DeviceAttributes(fetchesMessages, 1234, 5678, null,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
accountAttributes,
deviceAttributes,
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, apnRegistrationId, gcmRegistrationId));
final LinkDeviceResponse response = resources.getJerseyTest()
@@ -339,7 +335,7 @@ class DeviceControllerTest {
}
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(false, 1234, 5678, null, null, true, requestCapabilities),
new DeviceAttributes(false, 1234, 5678, null, requestCapabilities),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
final int expectedStatus =
@@ -392,7 +388,7 @@ class DeviceControllerTest {
.collect(Collectors.toSet());
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(false, 1234, 5678, null, null, true, requestCapabilities),
new DeviceAttributes(false, 1234, 5678, null, requestCapabilities),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
try (final Response response = resources.getJerseyTest()
@@ -430,7 +426,7 @@ class DeviceControllerTest {
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(false, 1234, 5678, null, null, true, null),
new DeviceAttributes(false, 1234, 5678, null, null),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
try (final Response response = resources.getJerseyTest()
@@ -472,11 +468,11 @@ class DeviceControllerTest {
when(asyncCommands.set(any(), any(), any())).thenReturn(MockRedisFuture.completedFuture(null));
final AccountAttributes accountAttributes = new AccountAttributes(true, 1234, 5678, null,
null, true, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
final DeviceAttributes deviceAttributes = new DeviceAttributes(true, 1234, 5678, null,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
accountAttributes,
deviceAttributes,
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.empty()));
try (final Response response = resources.getJerseyTest()
@@ -517,7 +513,7 @@ class DeviceControllerTest {
when(commands.get(anyString())).thenReturn("");
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(false, 1234, 5678, null, null, true, null),
new DeviceAttributes(false, 1234, 5678, null, null),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
try (final Response response = resources.getJerseyTest()
@@ -566,7 +562,7 @@ class DeviceControllerTest {
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
final LinkDeviceRequest request = new LinkDeviceRequest(deviceCode.token(),
new AccountAttributes(fetchesMessages, 1234, 5678, null, null, true, null),
new DeviceAttributes(fetchesMessages, 1234, 5678, null, null),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, apnRegistrationId, gcmRegistrationId));
try (final Response response = resources.getJerseyTest()
@@ -614,7 +610,7 @@ class DeviceControllerTest {
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(pniIdentityKey);
final LinkDeviceRequest request = new LinkDeviceRequest(deviceCode.token(),
new AccountAttributes(true, 1234, 5678, null, null, true, null),
new DeviceAttributes(true, 1234, 5678, null, null),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.empty()));
try (final Response response = resources.getJerseyTest()
@@ -674,7 +670,7 @@ class DeviceControllerTest {
when(accountsManager.checkDeviceLinkingToken(anyString())).thenReturn(Optional.of(AuthHelper.VALID_UUID));
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(true, 1234, 5678, null, null, true, null),
new DeviceAttributes(true, 1234, 5678, null, null),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.empty()));
try (final Response response = resources.getJerseyTest()
@@ -707,7 +703,7 @@ class DeviceControllerTest {
when(accountsManager.checkDeviceLinkingToken(anyString())).thenReturn(Optional.of(AuthHelper.VALID_UUID));
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(true, 1234, 5678, null, null, true, null),
new DeviceAttributes(true, 1234, 5678, null, null),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.empty()));
try (final Response response = resources.getJerseyTest()
@@ -766,7 +762,7 @@ class DeviceControllerTest {
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(false, 1234, 5678, TestRandomUtil.nextBytes(512), null, true, null),
new DeviceAttributes(false, 1234, 5678, TestRandomUtil.nextBytes(512), null),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
try (final Response response = resources.getJerseyTest()
@@ -811,7 +807,7 @@ class DeviceControllerTest {
when(asyncCommands.set(any(), any(), any())).thenReturn(MockRedisFuture.completedFuture(null));
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(false, registrationId, pniRegistrationId, null, null, true, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES),
new DeviceAttributes(false, registrationId, pniRegistrationId, null, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.of(new ApnRegistrationId("apn")), Optional.empty()));
try (final Response response = resources.getJerseyTest()
@@ -1465,14 +1461,14 @@ class DeviceControllerTest {
@NullSource
@ValueSource(strings = {""})
void linkDeviceMissingVerificationCode(final String verificationCode) {
final AccountAttributes accountAttributes = new AccountAttributes(true, 1234, 5678, null,
null, true, Set.of());
final DeviceAttributes deviceAttributes = new DeviceAttributes(true, 1234, 5678, null,
Set.of());
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final LinkDeviceRequest request = new LinkDeviceRequest(verificationCode,
accountAttributes,
deviceAttributes,
new DeviceActivationRequest(
KeysHelper.signedECPreKey(1, aciIdentityKeyPair),
KeysHelper.signedECPreKey(2, pniIdentityKeyPair),
@@ -37,6 +37,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@@ -59,6 +60,7 @@ import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.entities.CheckKeysRequest;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
@@ -93,20 +95,22 @@ import org.whispersystems.textsecuregcm.util.TestClock;
class KeysControllerTest {
private static final String EXISTS_NUMBER = "+14152222222";
private static final UUID EXISTS_UUID = UUID.randomUUID();
private static final UUID EXISTS_PNI = UUID.randomUUID();
private static final UUID EXISTS_UUID = UUID.randomUUID();
private static final UUID EXISTS_PNI = UUID.randomUUID();
private static final AciServiceIdentifier EXISTS_ACI = new AciServiceIdentifier(EXISTS_UUID);
private static final PniServiceIdentifier EXISTS_PNI_SERVICE_ID = new PniServiceIdentifier(EXISTS_PNI);
private static final byte[] EXISTS_UAK = Arrays.copyOf(
"1337".getBytes(), UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
private static final UUID OTHER_UUID = UUID.randomUUID();
private static final UUID OTHER_UUID = UUID.randomUUID();
private static final AciServiceIdentifier OTHER_ACI = new AciServiceIdentifier(OTHER_UUID);
private static final UUID NOT_EXISTS_UUID = UUID.randomUUID();
private static final UUID NOT_EXISTS_UUID = UUID.randomUUID();
private static final AciServiceIdentifier NOT_EXISTS_ACI = new AciServiceIdentifier(NOT_EXISTS_UUID);
private static final byte SAMPLE_DEVICE_ID = 1;
private static final int SAMPLE_REGISTRATION_ID = 999;
private static final int SAMPLE_REGISTRATION_ID = 999;
private static final int SAMPLE_PNI_REGISTRATION_ID = 1717;
private final ECKeyPair IDENTITY_KEY_PAIR = ECKeyPair.generate();
@@ -218,7 +222,7 @@ class KeysControllerTest {
when(existsAccount.getIdentityKey(IdentityType.ACI)).thenReturn(IDENTITY_KEY);
when(existsAccount.getIdentityKey(IdentityType.PNI)).thenReturn(PNI_IDENTITY_KEY);
when(existsAccount.getNumber()).thenReturn(EXISTS_NUMBER);
when(existsAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of("1337".getBytes()));
when(existsAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(EXISTS_UAK));
when(accounts.getByServiceIdentifier(any())).thenReturn(Optional.empty());
when(accounts.getByServiceIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
@@ -389,7 +393,7 @@ class KeysControllerTest {
.target(String.format("/v2/keys/%s/1", EXISTS_UUID))
.queryParam("pq", "true")
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("1337".getBytes()))
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader(EXISTS_UAK))
.get(PreKeyResponse.class);
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI));
@@ -448,7 +452,7 @@ class KeysControllerTest {
.header(HeaderUtils.GROUP_SEND_TOKEN, AuthHelper.validGroupSendTokenHeader(serverSecretParams, List.of(authorizedTarget), expiration));
if (includeUak) {
builder = builder.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("1337".getBytes()));
builder = builder.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader(EXISTS_UAK));
}
Response response = builder.get();
@@ -501,7 +505,7 @@ class KeysControllerTest {
Response result = resources.getJerseyTest()
.target(String.format("/v2/keys/%s/*", EXISTS_UUID))
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("1337".getBytes()))
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader(EXISTS_UAK))
.get();
assertThat(result).isNotNull();
@@ -513,7 +517,7 @@ class KeysControllerTest {
Response response = resources.getJerseyTest()
.target(String.format("/v2/keys/%s/1", EXISTS_UUID))
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("9999".getBytes()))
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader(Arrays.copyOf("9999".getBytes(), UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH)))
.get();
assertThat(response.getStatus()).isEqualTo(401);
@@ -425,6 +425,26 @@ class MessageControllerTest {
}
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testSingleDeviceCurrentUnidentifiedEmptyMessages(
final boolean story) throws Exception {
try (final Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/%s", SINGLE_DEVICE_UUID))
.queryParam("story", story)
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, Base64.getEncoder().encodeToString(UNIDENTIFIED_ACCESS_BYTES))
.put(Entity.entity(SystemMapper.jsonMapper().readValue(jsonFixture("fixtures/current_message_empty.json"),
IncomingMessageList.class),
MediaType.APPLICATION_JSON_TYPE))) {
assertThat("Unprocessable entity", response.getStatus(), is(equalTo(422)));
verifyNoMoreInteractions(messageSender);
}
}
@ParameterizedTest
@MethodSource
void testSingleDeviceCurrentGroupSendEndorsement(
@@ -469,32 +489,23 @@ class MessageControllerTest {
private static Stream<Arguments> testSingleDeviceCurrentGroupSendEndorsement() {
return Stream.of(
// valid endorsement
Arguments.of(SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ACI_ID, Duration.ofHours(1), false, false, 200),
Arguments.argumentSet("valid endorsement", SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ACI_ID, Duration.ofHours(1), false, false, 200),
// expired endorsement, not authorized
Arguments.of(SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ACI_ID, Duration.ofHours(-1), false, false, 401),
Arguments.argumentSet("expired endorsement, not authorized", SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ACI_ID, Duration.ofHours(-1), false, false, 401),
// endorsement for the wrong recipient, not authorized
Arguments.of(SINGLE_DEVICE_ACI_ID, NONEXISTENT_ACI_ID, Duration.ofHours(1), false, false, 401),
Arguments.argumentSet("endorsement for the wrong recipient, not authorized", SINGLE_DEVICE_ACI_ID, NONEXISTENT_ACI_ID, Duration.ofHours(1), false, false, 401),
// expired endorsement for the wrong recipient, not authorized
Arguments.of(SINGLE_DEVICE_ACI_ID, NONEXISTENT_ACI_ID, Duration.ofHours(-1), false, false, 401),
Arguments.argumentSet("expired endorsement for the wrong recipient, not authorized", SINGLE_DEVICE_ACI_ID, NONEXISTENT_ACI_ID, Duration.ofHours(-1), false, false, 401),
// valid endorsement for the right recipient but they aren't registered, not found
Arguments.of(NONEXISTENT_ACI_ID, NONEXISTENT_ACI_ID, Duration.ofHours(1), false, false, 404),
Arguments.argumentSet("valid endorsement for the right recipient but they aren't registered, not found", NONEXISTENT_ACI_ID, NONEXISTENT_ACI_ID, Duration.ofHours(1), false, false, 404),
// expired endorsement for the right recipient but they aren't registered, not authorized (NOT not found)
Arguments.of(NONEXISTENT_ACI_ID, NONEXISTENT_ACI_ID, Duration.ofHours(-1), false, false, 401),
Arguments.argumentSet("expired endorsement for the right recipient but they aren't registered, not authorized (NOT not found)", NONEXISTENT_ACI_ID, NONEXISTENT_ACI_ID, Duration.ofHours(-1), false, false, 401),
// valid endorsement but also a UAK, bad request
Arguments.of(SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ACI_ID, Duration.ofHours(1), true, false, 400),
Arguments.argumentSet("valid endorsement but also a UAK, bad request", SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ACI_ID, Duration.ofHours(1), true, false, 400),
// valid endorsement on a story, bad request
Arguments.of(SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ACI_ID, Duration.ofHours(1), false, true, 400),
Arguments.argumentSet("valid endorsement on a story, bad request", SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ACI_ID, Duration.ofHours(1), false, true, 400),
// valid endorsement on a story with a UAK, bad request
Arguments.of(SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ACI_ID, Duration.ofHours(1), true, true, 400));
Arguments.argumentSet("valid endorsement on a story with a UAK, bad request", SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ACI_ID, Duration.ofHours(1), true, true, 400));
}
@ParameterizedTest
@@ -39,6 +39,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HexFormat;
@@ -76,6 +77,7 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequestContext;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
@@ -291,7 +293,9 @@ class ProfileControllerTest {
final Response response = resources.getJerseyTest()
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO)
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("incorrect".getBytes()))
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY,
AuthHelper.getUnidentifiedAccessHeader(
Arrays.copyOf("incorrect".getBytes(), UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH)))
.get();
assertThat(response.getStatus()).isEqualTo(401);
@@ -418,7 +422,8 @@ class ProfileControllerTest {
final Response response = resources.getJerseyTest()
.target("/v1/profile/" + AuthHelper.VALID_PNI_TWO)
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("incorrect".getBytes()))
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader(
Arrays.copyOf("incorrect".getBytes(), UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH)))
.get();
assertThat(response.getStatus()).isEqualTo(401);
@@ -89,6 +89,7 @@ import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@ExtendWith(DropwizardExtensionsSupport.class)
class RegistrationControllerTest {
@@ -441,6 +442,36 @@ class RegistrationControllerTest {
.argumentsForNextParameter(registrationLockErrors);
}
@Test
void registrationLockOnAlternatePhoneNumberForm() throws Exception {
final String newFormatBeninNumber = PhoneNumberUtil.getInstance()
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String oldFormatBeninNumber = newFormatBeninNumber.replaceFirst("01", "");
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], newFormatBeninNumber, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
final Account account = mock(Account.class);
when(accountsManager.getByE164(oldFormatBeninNumber)).thenReturn(Optional.of(account));
when(accountsManager.getByE164(newFormatBeninNumber)).thenReturn(Optional.empty());
when(account.hasCapability(DeviceCapability.TRANSFER)).thenReturn(false);
doThrow(new WebApplicationException(RegistrationLockError.MISMATCH.getExpectedStatus()))
.when(registrationLockVerificationManager).verifyRegistrationLock(any(), any(), any(), any(), any());
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(newFormatBeninNumber, PASSWORD));
try (final Response response = request.post(Entity.json(requestJson("sessionId")))) {
assertEquals(RegistrationLockError.MISMATCH.getExpectedStatus(), response.getStatus());
}
}
@ParameterizedTest
@CsvSource({
@@ -871,10 +902,12 @@ class RegistrationControllerTest {
final Set<DeviceCapability> deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES;
final AccountAttributes fetchesMessagesAccountAttributes =
new AccountAttributes(true, registrationId, pniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, deviceCapabilities);
new AccountAttributes(true, registrationId, pniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, deviceCapabilities)
.setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16));
final AccountAttributes pushAccountAttributes =
new AccountAttributes(false, registrationId, pniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, deviceCapabilities);
new AccountAttributes(false, registrationId, pniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, deviceCapabilities)
.setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16));
final String apnsToken = "apns-token";
final String gcmToken = "gcm-token";
@@ -987,7 +1020,8 @@ class RegistrationControllerTest {
final AccountAttributes accountAttributes = new AccountAttributes(true, registrationId, pniRegistrationId,
"name".getBytes(StandardCharsets.UTF_8), REGLOCK,
true, deviceCapabilities);
true, deviceCapabilities)
.setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16));
return new RegistrationRequest(
Base64.getEncoder().encodeToString(sessionId.getBytes(StandardCharsets.UTF_8)),
@@ -0,0 +1,53 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Base64;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class AccountAttributesTest {
private static final ObjectMapper mapper = SystemMapper.jsonMapper();
@Test
void testSerializationDeserializationRoundTrip() throws Exception {
final String originalJson = testJson();
final AccountAttributes attributes = mapper.readValue(originalJson, AccountAttributes.class);
assertEquals(originalJson, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(attributes));
}
private static String testJson() {
return String.format("""
{
"fetchesMessages" : false,
"registrationId" : 123,
"pniRegistrationId" : 456,
"name" : "%s",
"capabilities" : {
"storage" : true
},
"registrationLock" : null,
"unidentifiedAccessKey" : "%s",
"unrestrictedUnidentifiedAccess" : false,
"discoverableByPhoneNumber" : true,
"recoveryPassword" : "%s"
}
""",
Base64.getEncoder().withoutPadding().encodeToString(TestRandomUtil.nextBytes(128)), // name
Base64.getEncoder().encodeToString(TestRandomUtil.nextBytes(16)), // unidentifiedAccessKey
Base64.getEncoder().encodeToString(TestRandomUtil.nextBytes(32)) // recoveryPassword
).trim();
}
}
@@ -8,11 +8,13 @@ package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -54,6 +56,7 @@ import org.signal.chat.account.SetRegistrationLockResponse;
import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
import org.signal.chat.account.SetUsernameLinkRequest;
import org.signal.chat.account.SetUsernameLinkResponse;
import org.signal.chat.account.SetZkCredentialKeyRequest;
import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
import org.signal.chat.errors.FailedPrecondition;
@@ -109,6 +112,8 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(rateLimiters.getUsernameSetLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getUsernameLinkOperationLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getSetZkCredentialKeyLimiter()).thenReturn(rateLimiter);
when(registrationRecoveryPasswordsManager.store(any(), any()))
.thenReturn(CompletableFuture.completedFuture(null));
@@ -712,4 +717,53 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
() -> authenticatedServiceStub().setRegistrationRecoveryPassword(
SetRegistrationRecoveryPasswordRequest.newBuilder().build()));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void setZkCredentialKey(final boolean matchesCurrentZkCredentialKey) {
final byte[] publicKey = TestRandomUtil.nextBytes(33);
final Account account = mock(Account.class);
if (matchesCurrentZkCredentialKey) {
when(account.getZkCredentialKey()).thenReturn(publicKey);
}
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
assertDoesNotThrow(() ->
authenticatedServiceStub().setZkCredentialKey(SetZkCredentialKeyRequest.newBuilder()
.setPublicKey(ByteString.copyFrom(publicKey))
.build()));
final int updateMethodCalls = matchesCurrentZkCredentialKey ? 0 : 1;
verify(accountsManager, times(updateMethodCalls)).update(eq(account), any(Consumer.class));
verify(account, times(updateMethodCalls)).setZkCredentialKey(aryEq(publicKey));
}
@Test
void setZkCredentialKeyRateLimited() throws Exception {
final byte[] publicKey = TestRandomUtil.nextBytes(33);
final Duration retryDuration = Duration.ofDays(1);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
doThrow(new RateLimitExceededException(retryDuration))
.when(rateLimiter).validate(AUTHENTICATED_ACI);
GrpcTestUtils.assertRateLimitExceeded(retryDuration, () ->
authenticatedServiceStub().setZkCredentialKey(SetZkCredentialKeyRequest.newBuilder()
.setPublicKey(ByteString.copyFrom(publicKey))
.build()));
verify(accountsManager, never()).update(any(Account.class), any(Consumer.class));
verify(account, never()).setZkCredentialKey(any());
}
}
@@ -576,7 +576,7 @@ class MessageSenderTest {
when(account.getDevices()).thenReturn(List.of(device));
when(account.isIdentifiedBy(serviceIdentifier)).thenReturn(true);
assertThrows(MismatchedDevicesException.class, () -> messageSender.sendMessages(account,
assertThrows(IllegalArgumentException.class, () -> messageSender.sendMessages(account,
serviceIdentifier,
Collections.emptyMap(),
Collections.emptyMap(),
@@ -479,6 +479,7 @@ class AccountsTest {
// the backup credential request and share-set are always preserved across account reclaims
existingAccount.setBackupCredentialRequests(TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32));
existingAccount.setZkCredentialKey(TestRandomUtil.nextBytes(32));
createAccount(existingAccount);
final Account secondAccount =
generateAccount(e164, UUID.randomUUID(), UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1)));
@@ -490,6 +491,7 @@ class AccountsTest {
.isEqualTo(existingAccount.getBackupCredentialRequest(BackupCredentialType.MESSAGES).orElseThrow());
assertThat(reclaimed.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElseThrow())
.isEqualTo(existingAccount.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElseThrow());
assertThat(reclaimed.getZkCredentialKey()).isEqualTo(existingAccount.getZkCredentialKey());
}
@Test
@@ -500,9 +502,11 @@ class AccountsTest {
final UUID existingPni = UUID.randomUUID();
final Account existingAccount = generateAccount(e164, existingUuid, existingPni, List.of(device));
// Backup vouchers should be carried over accross re-registration
// Backup vouchers should be carried over across re-registration
final Account.BackupVoucher bv = new Account.BackupVoucher(1, Instant.now().plus(Duration.ofDays(1)));
existingAccount.setBackupVoucher(bv);
// ZK credential keys should be carried over across re-registration
existingAccount.setZkCredentialKey(TestRandomUtil.nextBytes(32));
createAccount(existingAccount);
@@ -16,6 +16,7 @@ import static org.mockito.Mockito.when;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@@ -25,8 +26,8 @@ import org.mockito.MockingDetails;
import org.mockito.stubbing.Stubbing;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceAttributes;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -122,11 +123,6 @@ public class AccountsHelper {
answer.getArgument(1, Device.class).setLastSeen(answer.getArgument(2, Long.class));
return mockAccountsManager.update(answer.getArgument(0, Account.class), account -> {});
});
when(mockAccountsManager.updateDeviceAuthentication(any(), any(), any())).thenAnswer(answer -> {
answer.getArgument(1, Device.class).setAuthTokenHash(answer.getArgument(2, SaltedTokenHash.class));
return mockAccountsManager.update(answer.getArgument(0, Account.class), account -> {});
});
}
public static void setupMockGet(final AccountsManager mockAccountsManager, final Set<Account> mockAccounts) {
@@ -203,7 +199,8 @@ public class AccountsHelper {
public static Account createAccount(final AccountsManager accountsManager, final String e164)
throws InterruptedException {
return createAccount(accountsManager, e164, new AccountAttributes());
return createAccount(accountsManager, e164, new AccountAttributes().setDeviceAttributes(
new DeviceAttributes(false, 1, 1, new byte[0], Collections.emptySet())));
}
public static Account createAccount(final AccountsManager accountsManager, final String e164, final AccountAttributes accountAttributes)
@@ -236,6 +236,7 @@ public class AuthHelper {
}
public static String getUnidentifiedAccessHeader(byte[] key) {
assert key.length == 16;
return Base64.getEncoder().encodeToString(key);
}
@@ -519,9 +519,6 @@ idlePrimaryDeviceReminder:
grpc:
port: 50051
grpcAllowList:
enableAll: true
asnTable:
s3Region: a-region
s3Bucket: a-bucket
@@ -0,0 +1,4 @@
{
"timestamp" : 1234,
"messages" : []
}