Use single bytes to represent TOTP key IDs and limit key IDs to [0, 127]

This commit is contained in:
Jon Chambers authored and Chris Eager committed 2026-08-25 11:27:38 -04:00
1 parent 4157cadf44
commit c612bd4b73
7 files changed
+128 -60

No files matched your search

@@ -577,7 +577,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public ConfirmTotpKeyResponse confirmTotpKey(final ConfirmTotpKeyRequest request) {
final Optional<Integer> maybeConfirmedTotpKeyId =
final Optional<Byte> maybeConfirmedTotpKeyId =
accountsManager.confirmPendingTotpKey(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
request.getOneTimePassword(),
clock.instant(),
@@ -610,17 +610,18 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public SetTotpKeyMetadataResponse setTotpKeyMetadata(final SetTotpKeyMetadataRequest request) {
final byte keyId = validateTotpKeyId(request.getKeyId());
try {
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
final Map<Integer, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
@Nullable final AnnotatedTotpKey existingKey = totpKeys.get(request.getKeyId());
final Map<Byte, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
@Nullable final AnnotatedTotpKey existingKey = totpKeys.get(keyId);
if (existingKey == null) {
throw new TotpKeyNotFoundException();
}
totpKeys.put(request.getKeyId(),
new AnnotatedTotpKey(existingKey.totpKey(), request.getMetadataCiphertext().toByteArray()));
totpKeys.put(keyId, new AnnotatedTotpKey(existingKey.totpKey(), request.getMetadataCiphertext().toByteArray()));
account.setTotpKeys(totpKeys);
});
@@ -637,9 +638,11 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public RemoveTotpKeyResponse removeTotpKey(final RemoveTotpKeyRequest request) {
final byte keyId = validateTotpKeyId(request.getKeyId());
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
final Map<Integer, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
totpKeys.remove(request.getKeyId());
final Map<Byte, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
totpKeys.remove(keyId);
account.setTotpKeys(totpKeys);
});
@@ -647,6 +650,14 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
return RemoveTotpKeyResponse.getDefaultInstance();
}
private byte validateTotpKeyId(final int keyId) {
if (keyId < 0 || keyId > Account.MAX_TOTP_KEY_ID) {
throw GrpcExceptions.invalidArguments("TOTP key ID out of range");
}
return (byte) keyId;
}
private static TotpParameters toGrpcTotpParameters(final org.whispersystems.textsecuregcm.storage.TotpParameters totpParameters) {
return TotpParameters.newBuilder()
.setAlgorithm(totpParameters.algorithm())
@@ -22,12 +22,15 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.IdentityKey;
@@ -46,6 +49,8 @@ import org.whispersystems.textsecuregcm.util.ZkCredentialPublicKeyAdapter;
@JsonFilter("Account")
public class Account {
public static final int MAX_TOTP_KEY_ID = Byte.MAX_VALUE;
private static final Logger logger = LoggerFactory.getLogger(Account.class);
@JsonProperty
@@ -161,7 +166,7 @@ public class Account {
private TotpKey pendingTotpKey;
@JsonProperty("totp")
private Map<Integer, AnnotatedTotpKey> totpKeys = Collections.emptyMap();
private Map<Byte, AnnotatedTotpKey> totpKeys = Collections.emptyMap();
@JsonIgnore
private boolean stale;
@@ -668,21 +673,23 @@ public class Account {
return Optional.ofNullable(pendingTotpKey);
}
public int getNextTotpKeyId() {
public byte getNextTotpKeyId() {
requireNotStale();
return totpKeys.keySet().stream()
.mapToInt(i -> i)
.max()
.orElse(-1) + 1;
final Set<Byte> usedKeys = new HashSet<>(totpKeys.keySet());
return (byte) IntStream.range(0, MAX_TOTP_KEY_ID + 1)
.filter(b -> !usedKeys.contains((byte) b))
.findFirst()
.orElseThrow(IllegalStateException::new);
}
public Map<Integer, AnnotatedTotpKey> getTotpKeys() {
public Map<Byte, AnnotatedTotpKey> getTotpKeys() {
requireNotStale();
return totpKeys;
}
public void setTotpKeys(final Map<Integer, AnnotatedTotpKey> totpKeys) {
public void setTotpKeys(final Map<Byte, AnnotatedTotpKey> totpKeys) {
requireNotStale();
this.totpKeys = totpKeys;
}
@@ -61,7 +61,6 @@ 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;
@@ -2060,7 +2059,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
/// otherwise
///
/// @see [#generatePendingTotpKey(UUID)
public Optional<Integer> confirmPendingTotpKey(final UUID accountIdentifier,
public Optional<Byte> confirmPendingTotpKey(final UUID accountIdentifier,
final int oneTimePassword,
final Instant timestamp,
final byte[] metadataCiphertext) {
@@ -2081,18 +2080,18 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final AtomicInteger keyId = new AtomicInteger();
update(accountIdentifier, account -> {
final Map<Integer, AnnotatedTotpKey> updatedTotpKeys = new HashMap<>(account.getTotpKeys());
final Map<Byte, AnnotatedTotpKey> updatedTotpKeys = new HashMap<>(account.getTotpKeys());
keyId.set(account.getNextTotpKeyId());
updatedTotpKeys.put(keyId.get(),
updatedTotpKeys.put((byte) keyId.get(),
new AnnotatedTotpKey(new TotpKey(pendingTotpKey.totpParameters(), pendingTotpKey.encodedKey()), metadataCiphertext));
account.setPendingTotpKey(null);
account.setTotpKeys(updatedTotpKeys);
});
return Optional.of(keyId.get());
return Optional.of((byte) keyId.get());
}
} catch (final InvalidKeyException e) {
ImpossibleEvents.logImpossible(logger, "Invalid pending TOTP key for account {}", accountIdentifier, e);
@@ -549,7 +549,7 @@ message ConfirmTotpKeyRequest {
message ConfirmTotpKeyResponse {
message KeyConfirmed {
// The account-specific identifier for the newly-confirmed TOTP key
uint32 key_id = 1;
uint32 key_id = 1 [(require.range) = {min: 0, max: 127}];
}
oneof response {
@@ -568,7 +568,7 @@ message ListTotpKeysRequest {}
message ListTotpKeysResponse {
message TotpKeyMetadata {
// The user-provided ciphertext for metadata associated with this TOTP key
bytes metadata_ciphertext = 1;
bytes metadata_ciphertext = 1 [(require.exactlySize) = 160];
// The TOTP parameters associated with this key
TotpParameters totp_parameters = 2;
@@ -579,7 +579,7 @@ message ListTotpKeysResponse {
message SetTotpKeyMetadataRequest {
// The account-specific identifier of the TOTP key to modify
uint32 key_id = 1;
uint32 key_id = 1 [(require.range) = {min: 0, max: 127}];
// The ciphertext of the new user-provided metadata to be attached to the
// identified key
@@ -601,7 +601,7 @@ message SetTotpKeyMetadataResponse {
message RemoveTotpKeyRequest {
// The account-specific identifier of the TOTP key to remove
uint32 key_id = 1;
uint32 key_id = 1 [(require.range) = {min: 0, max: 127}];
}
message RemoveTotpKeyResponse {
@@ -1148,7 +1148,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Test
void confirmTotpKey() {
final int keyId = 17;
final byte keyId = 17;
final int oneTimePassword = 123456;
final byte[] metadataCiphertext = TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE);
@@ -1188,9 +1188,9 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Test
void listTotpKeys() {
final Map<Integer, AnnotatedTotpKey> totpKeys = Map.of(
1, generateRandomAnnotatedTotpKey(),
2, generateRandomAnnotatedTotpKey());
final Map<Byte, AnnotatedTotpKey> totpKeys = Map.of(
(byte) 1, generateRandomAnnotatedTotpKey(),
(byte) 2, generateRandomAnnotatedTotpKey());
final Account account = mock(Account.class);
when(account.getTotpKeys()).thenReturn(totpKeys);
@@ -1208,7 +1208,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
.build();
final Map<Integer, ListTotpKeysResponse.TotpKeyMetadata> expectedTotpKeys = totpKeys.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> ListTotpKeysResponse.TotpKeyMetadata.newBuilder()
.collect(Collectors.toMap(entry -> entry.getKey().intValue(), entry -> ListTotpKeysResponse.TotpKeyMetadata.newBuilder()
.setTotpParameters(expectedTotpParameters)
.setMetadataCiphertext(ByteString.copyFrom(entry.getValue().metadataCiphertext()))
.build()));
@@ -1218,7 +1218,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Test
void setTotpKeyMetadata() {
final int keyId = ThreadLocalRandom.current().nextInt();
final byte keyId = (byte) ThreadLocalRandom.current().nextInt(Account.MAX_TOTP_KEY_ID);
final byte[] updatedMetadata = TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE);
final AnnotatedTotpKey existingTotpKey = generateRandomAnnotatedTotpKey();
@@ -1248,7 +1248,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final SetTotpKeyMetadataResponse response =
authenticatedServiceStub().setTotpKeyMetadata(SetTotpKeyMetadataRequest.newBuilder()
.setKeyId(ThreadLocalRandom.current().nextInt())
.setKeyId(ThreadLocalRandom.current().nextInt(Account.MAX_TOTP_KEY_ID))
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE)))
.build());
@@ -1265,11 +1265,20 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
}
@Test
void removeTotpKey() {
final int retainedKeyId = 1;
final int removedKeyId = 2;
void setTotpKeyMetadataKeyIdOutOfRange() {
GrpcTestUtils.assertStatusInvalidArgument(
() -> authenticatedServiceStub().setTotpKeyMetadata(SetTotpKeyMetadataRequest.newBuilder()
.setKeyId(Account.MAX_TOTP_KEY_ID + 1)
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE)))
.build()));
}
final Map<Integer, AnnotatedTotpKey> initialKeys = Map.of(
@Test
void removeTotpKey() {
final byte retainedKeyId = 1;
final byte removedKeyId = 2;
final Map<Byte, AnnotatedTotpKey> initialKeys = Map.of(
retainedKeyId, generateRandomAnnotatedTotpKey(),
removedKeyId, generateRandomAnnotatedTotpKey());
@@ -1287,6 +1296,14 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
verify(account).setTotpKeys(Map.of(retainedKeyId, initialKeys.get(retainedKeyId)));
}
@Test
void removeTotpKeyIdOutOfRange() {
GrpcTestUtils.assertStatusInvalidArgument(
() -> authenticatedServiceStub().removeTotpKey(RemoveTotpKeyRequest.newBuilder()
.setKeyId(Account.MAX_TOTP_KEY_ID + 1)
.build()));
}
private static AnnotatedTotpKey generateRandomAnnotatedTotpKey() {
return new AnnotatedTotpKey(new TotpKey(AccountsManager.TOTP_PARAMETERS, TestRandomUtil.nextBytes(32)),
TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE));
@@ -27,12 +27,16 @@ import java.util.Base64;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.BeforeEach;
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.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestClock;
@@ -282,21 +286,51 @@ class AccountTest {
assertThat(deserializedBase64Cpv.getCurrentProfileVersion()).isPresent().hasValue(version);
}
@Test
void getNextTotpKeyId() {
assertEquals(0, new Account().getNextTotpKeyId());
@ParameterizedTest
@MethodSource
void getNextTotpKeyId(final List<Byte> existingKeyIds, final byte expectedNextKeyId) {
final Account account = new Account();
account.setTotpKeys(existingKeyIds.stream()
.collect(Collectors.toMap(keyId -> keyId, _ -> new AnnotatedTotpKey(new TotpKey(
new TotpParameters(
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA256,
HmacOneTimePasswordGenerator.DEFAULT_PASSWORD_LENGTH,
TimeBasedOneTimePasswordGenerator.DEFAULT_TIME_STEP),
TestRandomUtil.nextBytes(16)),
TestRandomUtil.nextBytes(16)))));
final AnnotatedTotpKey totpKey = new AnnotatedTotpKey(new TotpKey(
new TotpParameters(
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA256,
HmacOneTimePasswordGenerator.DEFAULT_PASSWORD_LENGTH,
TimeBasedOneTimePasswordGenerator.DEFAULT_TIME_STEP),
TestRandomUtil.nextBytes(16)),
TestRandomUtil.nextBytes(16));
assertEquals(expectedNextKeyId, account.getNextTotpKeyId());
}
final Account accountWithTotpKey = new Account();
accountWithTotpKey.setTotpKeys(Map.of(0, totpKey));
private static List<Arguments> getNextTotpKeyId() {
final byte unclaimedId = 17;
assertEquals(1, accountWithTotpKey.getNextTotpKeyId());
final List<Byte> mostIdsTaken = IntStream.range(0, Account.MAX_TOTP_KEY_ID)
.filter(i -> i != unclaimedId)
.mapToObj(i -> (byte) i)
.toList();
return List.of(
Arguments.argumentSet("No existing keys", List.of(), (byte) 0),
Arguments.argumentSet("Single existing key", List.of((byte) 0), (byte) 1),
Arguments.argumentSet("Multiple existing keys", List.of((byte) 0, (byte) 1), (byte) 2),
Arguments.argumentSet("ID wraparound", List.of((byte) 0, (byte) 255), (byte) 1),
Arguments.argumentSet("Most IDs taken", mostIdsTaken, unclaimedId)
);
}
void getNextTotpKeyNoneAvailable() {
final Account account = new Account();
account.setTotpKeys(IntStream.range(0, Account.MAX_TOTP_KEY_ID)
.mapToObj(i -> (byte) i)
.collect(Collectors.toMap(keyId -> keyId, _ -> new AnnotatedTotpKey(new TotpKey(
new TotpParameters(
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA256,
HmacOneTimePasswordGenerator.DEFAULT_PASSWORD_LENGTH,
TimeBasedOneTimePasswordGenerator.DEFAULT_TIME_STEP),
TestRandomUtil.nextBytes(16)),
TestRandomUtil.nextBytes(16)))));
assertThrows(IllegalStateException.class, account::getNextTotpKeyId);
}
}
@@ -1957,7 +1957,7 @@ class AccountsManagerTest {
when(account.getTotpKeys()).thenReturn(IntStream.range(0, AccountsManager.MAX_TOTP_KEYS)
.boxed()
.collect(Collectors.toMap(keyId -> keyId, _ -> new AnnotatedTotpKey(
.collect(Collectors.toMap(Integer::byteValue, _ -> new AnnotatedTotpKey(
new TotpKey(AccountsManager.TOTP_PARAMETERS, TestRandomUtil.nextBytes(16)),
TestRandomUtil.nextBytes(16)))));
@@ -1979,7 +1979,7 @@ class AccountsManagerTest {
.thenReturn(Optional.of(account));
final TotpKey pendingTotpKey = accountsManager.generatePendingTotpKey(accountIdentifier);
final int nextTotpKeyId = ThreadLocalRandom.current().nextInt();
final byte nextTotpKeyId = (byte) ThreadLocalRandom.current().nextInt();
when(account.getPendingTotpKey()).thenReturn(Optional.of(pendingTotpKey));
when(account.getNextTotpKeyId()).thenReturn(nextTotpKeyId);
@@ -2019,11 +2019,11 @@ class AccountsManagerTest {
TestRandomUtil.nextBytes(16));
}
final int keyId = 17;
final byte keyId = 17;
when(account.getPendingTotpKey()).thenReturn(Optional.empty());
when(account.getTotpKeys()).thenReturn(Map.of(
keyId - 1, confirmedTotpKey,
(byte) (keyId - 1), confirmedTotpKey,
keyId, confirmedTotpKey));
final TimeBasedOneTimePasswordGenerator totpGenerator =
@@ -2079,7 +2079,7 @@ class AccountsManagerTest {
.thenReturn(Optional.of(account));
final TotpKey pendingTotpKey = accountsManager.generatePendingTotpKey(accountIdentifier);
final int nextTotpKeyId = ThreadLocalRandom.current().nextInt();
final byte nextTotpKeyId = (byte) ThreadLocalRandom.current().nextInt();
when(account.getPendingTotpKey()).thenReturn(Optional.of(pendingTotpKey));
when(account.getNextTotpKeyId()).thenReturn(nextTotpKeyId);
@@ -2103,7 +2103,7 @@ class AccountsManagerTest {
@ParameterizedTest
@MethodSource
void verifyTotp(final Map<Integer, AnnotatedTotpKey> totpKeys,
void verifyTotp(final Map<Byte, AnnotatedTotpKey> totpKeys,
final Instant timestamp,
@Nullable final Integer oneTimePassword,
final boolean expectVerified) {
@@ -2145,16 +2145,16 @@ class AccountsManagerTest {
Collections.emptyMap(), timestamp, 123456, false),
Arguments.argumentSet("Has key, correct password provided",
Map.of(1, totpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp), true),
Map.of((byte) 1, totpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp), true),
Arguments.argumentSet("Has key, incorrect password provided",
Map.of(1, totpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp) + 1, false),
Map.of((byte) 1, totpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp) + 1, false),
Arguments.argumentSet("Has key, no password provided",
Map.of(1, totpKey), timestamp, null, false),
Map.of((byte) 1, totpKey), timestamp, null, false),
Arguments.argumentSet("Has multiple keys, correct password provided for one key",
Map.of(1, totpKey, 2, secondTotpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp), true)
Map.of((byte) 1, totpKey, (byte) 2, secondTotpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp), true)
);
}
@@ -2176,7 +2176,7 @@ class AccountsManagerTest {
AccountsManager.TOTP_PARAMETERS.algorithm());
final Account account = mock(Account.class);
when(account.getTotpKeys()).thenReturn(Map.of(1, totpKey));
when(account.getTotpKeys()).thenReturn(Map.of((byte) 1, totpKey));
final Instant beginningOfTotpWindow =
Instant.ofEpochMilli((Instant.now().toEpochMilli() / AccountsManager.TOTP_PARAMETERS.timeStep().toMillis()) *