replace deprecated apache RandomUtils

This commit is contained in:
Ravi Khadiwala 2023-12-04 13:15:10 -06:00 committed by ravi-signal
parent 37e3bcfc3e
commit 331bbdd4e6
38 changed files with 274 additions and 351 deletions

View File

@ -11,6 +11,13 @@
<artifactId>integration-tests</artifactId>
<dependencies>
<dependency>
<groupId>org.whispersystems.textsecure</groupId>
<artifactId>service</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
</dependency>
<dependency>
<groupId>org.whispersystems.textsecure</groupId>
<artifactId>service</artifactId>

View File

@ -24,7 +24,6 @@ import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Executors;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.tuple.Pair;
@ -48,6 +47,7 @@ import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
public final class Operations {
@ -67,8 +67,8 @@ public final class Operations {
}
public static TestUser newRegisteredUser(final String number) {
final byte[] registrationPassword = RandomUtils.nextBytes(32);
final String accountPassword = Base64.getEncoder().encodeToString(RandomUtils.nextBytes(32));
final byte[] registrationPassword = TestRandomUtil.nextBytes(32);
final String accountPassword = Base64.getEncoder().encodeToString(TestRandomUtil.nextBytes(32));
final TestUser user = TestUser.create(number, accountPassword, registrationPassword);
final AccountAttributes accountAttributes = user.accountAttributes();

View File

@ -14,7 +14,7 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.RandomUtils;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.IdentityKeyPair;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
@ -58,7 +58,7 @@ public class TestUser {
final int registrationId = KeyHelper.generateRegistrationId(false);
final int pniRegistrationId = KeyHelper.generateRegistrationId(false);
// uak
final byte[] unidentifiedAccessKey = RandomUtils.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
return new TestUser(
registrationId,

View File

@ -12,13 +12,13 @@ import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsSelector.CredentialInfo;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.MutableClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
public class ExternalServiceCredentialsSelectorTest {
@ -28,15 +28,15 @@ public class ExternalServiceCredentialsSelectorTest {
private static final ExternalServiceCredentialsGenerator GEN1 =
ExternalServiceCredentialsGenerator
.builder(RandomUtils.nextBytes(32))
.builder(TestRandomUtil.nextBytes(32))
.prependUsername(true)
.withClock(CLOCK)
.build();
private static final ExternalServiceCredentialsGenerator GEN2 =
ExternalServiceCredentialsGenerator
.builder(RandomUtils.nextBytes(32))
.withUserDerivationKey(RandomUtils.nextBytes(32))
.builder(TestRandomUtil.nextBytes(32))
.withUserDerivationKey(TestRandomUtil.nextBytes(32))
.prependUsername(false)
.withDerivedUsernameTruncateLength(16)
.withClock(CLOCK)

View File

@ -22,7 +22,6 @@ import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomUtils;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.ThrowableAssert;
import org.junit.jupiter.api.BeforeEach;
@ -31,7 +30,6 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mockito;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequestContext;
@ -42,10 +40,11 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.tests.util.ExperimentHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
public class BackupAuthManagerTest {
private final UUID aci = UUID.randomUUID();
private final byte[] backupKey = RandomUtils.nextBytes(32);
private final byte[] backupKey = TestRandomUtil.nextBytes(32);
private final TestClock clock = TestClock.now();
private final BackupAuthTestUtil backupAuthTestUtil = new BackupAuthTestUtil(clock);

View File

@ -32,7 +32,6 @@ import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nullable;
import org.apache.commons.lang3.RandomUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
@ -48,6 +47,7 @@ import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
@ -62,7 +62,7 @@ public class BackupManagerTest {
private final BackupAuthTestUtil backupAuthTestUtil = new BackupAuthTestUtil(testClock);
private final Cdn3BackupCredentialGenerator tusCredentialGenerator = mock(Cdn3BackupCredentialGenerator.class);
private final RemoteStorageManager remoteStorageManager = mock(RemoteStorageManager.class);
private final byte[] backupKey = RandomUtils.nextBytes(32);
private final byte[] backupKey = TestRandomUtil.nextBytes(32);
private final UUID aci = UUID.randomUUID();
private BackupManager backupManager;
@ -89,7 +89,7 @@ public class BackupManagerTest {
final Instant now = Instant.ofEpochSecond(Duration.ofDays(1).getSeconds());
testClock.pin(now);
final AuthenticatedBackupUser backupUser = backupUser(RandomUtils.nextBytes(16), backupTier);
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), backupTier);
final String encodedBackupId = Base64.getUrlEncoder().encodeToString(hashedBackupId(backupUser.backupId()));
backupManager.createMessageBackupUploadDescriptor(backupUser).join();
@ -108,7 +108,7 @@ public class BackupManagerTest {
@ParameterizedTest
@EnumSource(mode = EnumSource.Mode.EXCLUDE, names = {"NONE"})
public void ttlRefresh(final BackupTier backupTier) {
final AuthenticatedBackupUser backupUser = backupUser(RandomUtils.nextBytes(16), backupTier);
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), backupTier);
final Instant tstart = Instant.ofEpochSecond(1).plus(Duration.ofDays(1));
final Instant tnext = tstart.plus(Duration.ofSeconds(1));
@ -133,7 +133,7 @@ public class BackupManagerTest {
final Instant tstart = Instant.ofEpochSecond(1).plus(Duration.ofDays(1));
final Instant tnext = tstart.plus(Duration.ofSeconds(1));
final AuthenticatedBackupUser backupUser = backupUser(RandomUtils.nextBytes(16), backupTier);
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), backupTier);
// create backup at t=tstart
testClock.pin(tstart);
@ -251,7 +251,7 @@ public class BackupManagerTest {
@Test
public void copySuccess() {
final AuthenticatedBackupUser backupUser = backupUser(RandomUtils.nextBytes(16), BackupTier.MEDIA);
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupTier.MEDIA);
when(tusCredentialGenerator.generateUpload(any(), any()))
.thenReturn(new MessageBackupUploadDescriptor(3, "def", Collections.emptyMap(), ""));
when(remoteStorageManager.copy(eq(URI.create("cdn3.example.org/attachments/abc")), eq(100), any(), any()))
@ -279,7 +279,7 @@ public class BackupManagerTest {
@Test
public void copyFailure() {
final AuthenticatedBackupUser backupUser = backupUser(RandomUtils.nextBytes(16), BackupTier.MEDIA);
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupTier.MEDIA);
when(tusCredentialGenerator.generateUpload(any(), any()))
.thenReturn(new MessageBackupUploadDescriptor(3, "def", Collections.emptyMap(), ""));
when(remoteStorageManager.copy(eq(URI.create("cdn3.example.org/attachments/abc")), eq(100), any(), any()))

View File

@ -13,7 +13,6 @@ import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import org.apache.commons.lang3.RandomUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
@ -22,6 +21,7 @@ import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
public class BackupsDbTest {
@ -43,7 +43,7 @@ public class BackupsDbTest {
@Test
public void trackMediaIdempotent() {
final AuthenticatedBackupUser backupUser = backupUser(RandomUtils.nextBytes(16), BackupTier.MEDIA);
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupTier.MEDIA);
this.backupsDb.trackMedia(backupUser, "abc".getBytes(StandardCharsets.UTF_8), 100).join();
assertDoesNotThrow(() ->
this.backupsDb.trackMedia(backupUser, "abc".getBytes(StandardCharsets.UTF_8), 100).join());
@ -51,7 +51,7 @@ public class BackupsDbTest {
@Test
public void trackMediaLengthChange() {
final AuthenticatedBackupUser backupUser = backupUser(RandomUtils.nextBytes(16), BackupTier.MEDIA);
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupTier.MEDIA);
this.backupsDb.trackMedia(backupUser, "abc".getBytes(StandardCharsets.UTF_8), 100).join();
CompletableFutureTestUtil.assertFailsWithCause(InvalidLengthException.class,
this.backupsDb.trackMedia(backupUser, "abc".getBytes(StandardCharsets.UTF_8), 99));
@ -59,7 +59,7 @@ public class BackupsDbTest {
@Test
public void trackMediaStats() {
final AuthenticatedBackupUser backupUser = backupUser(RandomUtils.nextBytes(16), BackupTier.MEDIA);
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupTier.MEDIA);
// add at least one message backup so we can describe it
backupsDb.addMessageBackup(backupUser).join();
int total = 0;

View File

@ -5,22 +5,21 @@
package org.whispersystems.textsecuregcm.backup;
import org.apache.commons.lang3.RandomUtils;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
public class Cdn3BackupCredentialGeneratorTest {
@Test
public void uploadGenerator() {
Cdn3BackupCredentialGenerator generator = new Cdn3BackupCredentialGenerator(new TusConfiguration(
new SecretBytes(RandomUtils.nextBytes(32)),
new SecretBytes(TestRandomUtil.nextBytes(32)),
"https://example.org/upload"));
final MessageBackupUploadDescriptor messageBackupUploadDescriptor = generator.generateUpload("subdir", "key");
@ -34,7 +33,7 @@ public class Cdn3BackupCredentialGeneratorTest {
@Test
public void readCredential() {
Cdn3BackupCredentialGenerator generator = new Cdn3BackupCredentialGenerator(new TusConfiguration(
new SecretBytes(RandomUtils.nextBytes(32)),
new SecretBytes(TestRandomUtil.nextBytes(32)),
"https://example.org/upload"));
final Map<String, String> headers = generator.readHeaders("subdir");

View File

@ -20,7 +20,6 @@ import java.security.cert.CertificateException;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
@ -37,13 +36,14 @@ import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@ExtendWith(DropwizardExtensionsSupport.class)
public class Cdn3RemoteStorageManagerTest {
private static byte[] HMAC_KEY = getRandomBytes(32);
private static byte[] AES_KEY = getRandomBytes(32);
private static byte[] IV = getRandomBytes(16);
private static byte[] HMAC_KEY = TestRandomUtil.nextBytes(32);
private static byte[] AES_KEY = TestRandomUtil.nextBytes(32);
private static byte[] IV = TestRandomUtil.nextBytes(16);
@RegisterExtension
private final WireMockExtension wireMock = WireMockExtension.newInstance()
@ -176,10 +176,4 @@ public class Cdn3RemoteStorageManagerTest {
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(AES_KEY, "AES"), new IvParameterSpec(IV));
return cipher.doFinal(encrypted, IV.length, encrypted.length - IV.length - mac.getMacLength());
}
private static byte[] getRandomBytes(int length) {
byte[] result = new byte[length];
ThreadLocalRandom.current().nextBytes(result);
return result;
}
}

View File

@ -19,10 +19,10 @@ import java.util.Map;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.constraints.NotEmpty;
import org.apache.commons.lang3.RandomUtils;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.util.ExactlySize;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
public class SecretsTest {
@ -51,10 +51,10 @@ public class SecretsTest {
@Test
public void testDeserialization() throws Exception {
final String secretString = "secret_string";
final byte[] secretBytes = RandomUtils.nextBytes(16);
final byte[] secretBytes = TestRandomUtil.nextBytes(16);
final String secretBytesBase64 = Base64.getEncoder().encodeToString(secretBytes);
final List<String> secretStringList = List.of("secret1", "secret2", "secret3");
final List<byte[]> secretBytesList = List.of(RandomUtils.nextBytes(16), RandomUtils.nextBytes(16), RandomUtils.nextBytes(16));
final List<byte[]> secretBytesList = List.of(TestRandomUtil.nextBytes(16), TestRandomUtil.nextBytes(16), TestRandomUtil.nextBytes(16));
final List<String> secretBytesListBase64 = secretBytesList.stream().map(Base64.getEncoder()::encodeToString).toList();
final Map<String, Secret<?>> storeMap = Map.of(
SECRET_REF, new SecretString(secretString),

View File

@ -42,7 +42,6 @@ import java.util.stream.Stream;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.RandomUtils;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.AfterEach;
@ -92,6 +91,7 @@ import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
@ExtendWith(DropwizardExtensionsSupport.class)
@ -423,7 +423,7 @@ class AccountControllerTest {
// make sure `update()` works
doReturn(AuthHelper.VALID_ACCOUNT).when(accountsManager).update(any(), any());
final Response put = builder.put(Entity.json(new EncryptedUsername(RandomUtils.nextBytes(payloadSize))));
final Response put = builder.put(Entity.json(new EncryptedUsername(TestRandomUtil.nextBytes(payloadSize))));
assertEquals(expectedStatus, put.getStatus());
}
@ -502,7 +502,7 @@ class AccountControllerTest {
if (validUuidInput && locateLinkByUuid) {
final Account account = mock(Account.class);
when(account.getEncryptedUsername()).thenReturn(Optional.of(RandomUtils.nextBytes(16)));
when(account.getEncryptedUsername()).thenReturn(Optional.of(TestRandomUtil.nextBytes(16)));
when(accountsManager.getByUsernameLinkHandle(UUID.fromString(uuid))).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
}
@ -781,7 +781,7 @@ class AccountControllerTest {
@Test
void testAccountsAttributesUpdateRecoveryPassword() {
final byte[] recoveryPassword = RandomUtils.nextBytes(32);
final byte[] recoveryPassword = TestRandomUtil.nextBytes(32);
final Response response =
resources.getJerseyTest()
.target("/v1/accounts/attributes/")

View File

@ -37,7 +37,6 @@ import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.RandomUtils;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.BeforeEach;
@ -65,6 +64,7 @@ import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@ExtendWith(DropwizardExtensionsSupport.class)
public class ArchiveControllerTest {
@ -87,7 +87,7 @@ public class ArchiveControllerTest {
.build();
private final UUID aci = UUID.randomUUID();
private final byte[] backupKey = RandomUtils.nextBytes(32);
private final byte[] backupKey = TestRandomUtil.nextBytes(32);
@BeforeEach
public void setUp() {
@ -306,7 +306,7 @@ public class ArchiveControllerTest {
return CompletableFuture.completedFuture(new BackupManager.StorageDescriptor(1, mediaId));
});
final byte[][] mediaIds = new byte[][]{RandomUtils.nextBytes(15), RandomUtils.nextBytes(15)};
final byte[][] mediaIds = new byte[][]{TestRandomUtil.nextBytes(15), TestRandomUtil.nextBytes(15)};
final Response r = resources.getJerseyTest()
.target("v1/archives/media/batch")
@ -318,17 +318,17 @@ public class ArchiveControllerTest {
new ArchiveController.RemoteAttachment(3, "abc"),
100,
mediaIds[0],
RandomUtils.nextBytes(32),
RandomUtils.nextBytes(32),
RandomUtils.nextBytes(16)),
TestRandomUtil.nextBytes(32),
TestRandomUtil.nextBytes(32),
TestRandomUtil.nextBytes(16)),
new ArchiveController.CopyMediaRequest(
new ArchiveController.RemoteAttachment(3, "def"),
200,
mediaIds[1],
RandomUtils.nextBytes(32),
RandomUtils.nextBytes(32),
RandomUtils.nextBytes(16))
TestRandomUtil.nextBytes(32),
TestRandomUtil.nextBytes(32),
TestRandomUtil.nextBytes(16))
))));
assertThat(r.getStatus()).isEqualTo(207);
final ArchiveController.CopyMediaBatchResponse copyResponse = r.readEntity(
@ -351,7 +351,7 @@ public class ArchiveControllerTest {
.thenReturn(CompletableFuture.completedFuture(
new AuthenticatedBackupUser(presentation.getBackupId(), BackupTier.MEDIA)));
final byte[][] mediaIds = IntStream.range(0, 3).mapToObj(i -> RandomUtils.nextBytes(15)).toArray(byte[][]::new);
final byte[][] mediaIds = IntStream.range(0, 3).mapToObj(i -> TestRandomUtil.nextBytes(15)).toArray(byte[][]::new);
when(backupManager.canStoreMedia(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(true));
when(backupManager.copyToBackup(any(), anyInt(), any(), anyInt(), any(), eq(mediaIds[0])))
@ -366,9 +366,9 @@ public class ArchiveControllerTest {
new ArchiveController.RemoteAttachment(3, "abc"),
100,
mediaId,
RandomUtils.nextBytes(32),
RandomUtils.nextBytes(32),
RandomUtils.nextBytes(16))
TestRandomUtil.nextBytes(32),
TestRandomUtil.nextBytes(32),
TestRandomUtil.nextBytes(16))
).toList();
Response r = resources.getJerseyTest()
@ -419,10 +419,10 @@ public class ArchiveControllerTest {
.mapToObj(i -> new ArchiveController.CopyMediaRequest(
new ArchiveController.RemoteAttachment(3, "abc"),
i + 1,
RandomUtils.nextBytes(15),
RandomUtils.nextBytes(32),
RandomUtils.nextBytes(32),
RandomUtils.nextBytes(16))
TestRandomUtil.nextBytes(15),
TestRandomUtil.nextBytes(32),
TestRandomUtil.nextBytes(32),
TestRandomUtil.nextBytes(16))
).toList())));
assertThat(response.getStatus()).isEqualTo(413);
}

View File

@ -26,7 +26,6 @@ import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import javax.ws.rs.core.Response;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.Condition;
@ -48,6 +47,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@ExtendWith(DropwizardExtensionsSupport.class)
class AttachmentControllerTest {
@ -65,7 +65,7 @@ class AttachmentControllerTest {
when(mgr.isEnrolled(AuthHelper.VALID_UUID_TWO, AttachmentControllerV4.CDN3_EXPERIMENT_NAME)).thenReturn(false);
});
private static final byte[] TUS_SECRET = getRandomBytes(32);
private static final byte[] TUS_SECRET = TestRandomUtil.nextBytes(32);
private static final String TUS_URL = "https://example.com/uploads";
public static final String RSA_PRIVATE_KEY_PEM;
@ -243,10 +243,4 @@ class AttachmentControllerTest {
assertThat(response.getStatus()).isEqualTo(401);
}
private static byte[] getRandomBytes(int length) {
byte[] result = new byte[length];
ThreadLocalRandom.current().nextBytes(result);
return result;
}
}

View File

@ -26,7 +26,6 @@ import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
@ -80,6 +79,7 @@ import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.VerificationCode;
@ExtendWith(DropwizardExtensionsSupport.class)
@ -124,10 +124,7 @@ class DeviceControllerTest {
.build();
private static byte[] generateLinkDeviceSecret() {
final byte[] linkDeviceSecret = new byte[32];
new SecureRandom().nextBytes(linkDeviceSecret);
return linkDeviceSecret;
return TestRandomUtil.nextBytes(32);
}
@BeforeEach

View File

@ -16,7 +16,6 @@ import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableSet;
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
import io.dropwizard.testing.junit5.ResourceExtension;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Instant;
import java.util.List;
@ -46,13 +45,12 @@ import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class DonationControllerTest {
private static final long nowEpochSeconds = 1_500_000_000L;
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
static BadgesConfiguration getBadgesConfiguration() {
return new BadgesConfiguration(
List.of(
@ -85,11 +83,8 @@ class DonationControllerTest {
redeemedReceiptsManager = mock(RedeemedReceiptsManager.class);
accountsManager = mock(AccountsManager.class);
AccountsHelper.setupMockUpdate(accountsManager);
receiptSerialBytes = new byte[ReceiptSerial.SIZE];
SECURE_RANDOM.nextBytes(receiptSerialBytes);
receiptSerial = new ReceiptSerial(receiptSerialBytes);
presentation = new byte[25];
SECURE_RANDOM.nextBytes(presentation);
receiptSerial = new ReceiptSerial(TestRandomUtil.nextBytes(ReceiptSerial.SIZE));
presentation = TestRandomUtil.nextBytes(25);
receiptCredentialPresentationFactory = mock(DonationController.ReceiptCredentialPresentationFactory.class);
receiptCredentialPresentation = mock(ReceiptCredentialPresentation.class);

View File

@ -28,7 +28,6 @@ import io.dropwizard.testing.junit5.ResourceExtension;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@ -112,6 +111,7 @@ import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
@ -224,9 +224,9 @@ class ProfileControllerTest {
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(capabilitiesAccount));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(capabilitiesAccount));
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] emoji = ProfileTestHelper.generateRandomByteArray(60);
final byte[] about = ProfileTestHelper.generateRandomByteArray(156);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] emoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
when(profilesManager.get(eq(AuthHelper.VALID_UUID), eq("someversion"))).thenReturn(Optional.empty());
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq("validversion"))).thenReturn(Optional.of(new VersionedProfile(
@ -411,7 +411,7 @@ class ProfileControllerTest {
@Test
void testSetProfileWantAvatarUpload() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
final ProfileAvatarUploadAttributes uploadAttributes = resources.getJerseyTest()
.target("/v1/profile/")
@ -439,7 +439,7 @@ class ProfileControllerTest {
@Test
void testSetProfileWantAvatarUploadWithBadProfileSize() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final byte[] name = ProfileTestHelper.generateRandomByteArray(82);
final byte[] name = TestRandomUtil.nextBytes(82);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile/")
@ -455,7 +455,7 @@ class ProfileControllerTest {
@Test
void testSetProfileWithoutAvatarUpload() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
@ -488,7 +488,7 @@ class ProfileControllerTest {
@Test
void testSetProfileWithAvatarUploadAndPreviousAvatar() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
resources.getJerseyTest()
.target("/v1/profile/")
@ -515,7 +515,7 @@ class ProfileControllerTest {
@Test
void testSetProfileClearPreviousAvatar() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile/")
@ -545,7 +545,7 @@ class ProfileControllerTest {
@Test
void testSetProfileWithSameAvatar() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile/")
@ -575,7 +575,7 @@ class ProfileControllerTest {
@Test
void testSetProfileClearPreviousAvatarDespiteSameAvatarFlagSet() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
try (final Response ignored = resources.getJerseyTest()
.target("/v1/profile/")
@ -603,7 +603,7 @@ class ProfileControllerTest {
@Test
void testSetProfileWithSameAvatarDespiteNoPreviousAvatar() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile/")
@ -634,7 +634,7 @@ class ProfileControllerTest {
void testSetProfileExtendedName() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
final byte[] name = ProfileTestHelper.generateRandomByteArray(285);
final byte[] name = TestRandomUtil.nextBytes(285);
resources.getJerseyTest()
.target("/v1/profile/")
@ -665,9 +665,9 @@ class ProfileControllerTest {
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] emoji = ProfileTestHelper.generateRandomByteArray(60);
final byte[] about = ProfileTestHelper.generateRandomByteArray(156);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] emoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile/")
@ -705,8 +705,8 @@ class ProfileControllerTest {
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] paymentAddress = ProfileTestHelper.generateRandomByteArray(582);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile")
@ -747,8 +747,8 @@ class ProfileControllerTest {
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] paymentAddress = ProfileTestHelper.generateRandomByteArray(582);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile")
@ -774,15 +774,15 @@ class ProfileControllerTest {
.thenReturn(List.of(AuthHelper.VALID_NUMBER_TWO.substring(0, 3)));
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] paymentAddress = ProfileTestHelper.generateRandomByteArray(582);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), any()))
.thenReturn(Optional.of(
new VersionedProfile("1", name, null, null, null,
existingPaymentAddressOnProfile ? ProfileTestHelper.generateRandomByteArray(582) : null,
existingPaymentAddressOnProfile ? TestRandomUtil.nextBytes(582) : null,
commitment.serialize())));
@ -825,9 +825,9 @@ class ProfileControllerTest {
@Test
void testGetProfileByVersion() throws RateLimitExceededException {
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] emoji = ProfileTestHelper.generateRandomByteArray(60);
final byte[] about = ProfileTestHelper.generateRandomByteArray(156);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] emoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq("validversion"))).thenReturn(Optional.of(new VersionedProfile(
"validversion", name, "profiles/validavatar", emoji, about, null, "validcommitmnet".getBytes())));
@ -860,8 +860,8 @@ class ProfileControllerTest {
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] paymentAddress = ProfileTestHelper.generateRandomByteArray(582);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile")
@ -880,7 +880,7 @@ class ProfileControllerTest {
@Test
void testGetProfileReturnsNoPaymentAddressIfCurrentVersionMismatch() {
final byte[] paymentAddress = ProfileTestHelper.generateRandomByteArray(582);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
when(profilesManager.get(AuthHelper.VALID_UUID_TWO, "validversion")).thenReturn(
Optional.of(new VersionedProfile(null, null, null, null, null, paymentAddress, null)));
@ -950,9 +950,9 @@ class ProfileControllerTest {
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] emoji = ProfileTestHelper.generateRandomByteArray(60);
final byte[] about = ProfileTestHelper.generateRandomByteArray(156);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] emoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile/")
@ -1063,8 +1063,7 @@ class ProfileControllerTest {
final ServerZkProfileOperations serverZkProfile = new ServerZkProfileOperations(serverSecretParams);
final ClientZkProfileOperations clientZkProfile = new ClientZkProfileOperations(serverPublicParams);
final byte[] profileKeyBytes = new byte[32];
new SecureRandom().nextBytes(profileKeyBytes);
final byte[] profileKeyBytes = TestRandomUtil.nextBytes(32);
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
@ -1131,8 +1130,7 @@ class ProfileControllerTest {
final ClientZkProfileOperations clientZkProfile = new ClientZkProfileOperations(serverPublicParams);
final byte[] profileKeyBytes = new byte[32];
new SecureRandom().nextBytes(profileKeyBytes);
final byte[] profileKeyBytes = TestRandomUtil.nextBytes(32);
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));

View File

@ -18,6 +18,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 OutgoingMessageEntityTest {
@ -27,8 +28,7 @@ class OutgoingMessageEntityTest {
final ServiceIdentifier destinationIdentifier,
@Nullable final UUID updatedPni) {
final byte[] messageContent = new byte[16];
new Random().nextBytes(messageContent);
final byte[] messageContent = TestRandomUtil.nextBytes(16);
final long messageTimestamp = System.currentTimeMillis();
final long serverTimestamp = messageTimestamp + 17;
@ -66,11 +66,7 @@ class OutgoingMessageEntityTest {
void entityPreservesEnvelope() {
final Random random = new Random();
final byte[] messageContent = new byte[16];
random.nextBytes(messageContent);
final byte[] reportSpamToken = new byte[8];
random.nextBytes(reportSpamToken);
final byte[] reportSpamToken = TestRandomUtil.nextBytes(8);
final Account account = new Account();
account.setUuid(UUID.randomUUID());

View File

@ -16,7 +16,6 @@ import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.net.InetSocketAddress;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
@ -40,6 +39,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.publisher.Mono;
@ -135,8 +135,7 @@ class AccountsAnonymousGrpcServiceTest extends
void lookupUsernameHash() {
final UUID accountIdentifier = UUID.randomUUID();
final byte[] usernameHash = new byte[AccountController.USERNAME_HASH_LENGTH];
new SecureRandom().nextBytes(usernameHash);
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(accountIdentifier);
@ -201,8 +200,7 @@ class AccountsAnonymousGrpcServiceTest extends
void lookupUsernameLink() {
final UUID linkHandle = UUID.randomUUID();
final byte[] usernameCiphertext = new byte[32];
new SecureRandom().nextBytes(usernameCiphertext);
final byte[] usernameCiphertext = TestRandomUtil.nextBytes(32);
final Account account = mock(Account.class);
when(account.getEncryptedUsername()).thenReturn(Optional.of(usernameCiphertext));

View File

@ -26,7 +26,6 @@ import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
@ -75,6 +74,7 @@ import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
import reactor.core.publisher.Mono;
@ -128,8 +128,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final String e164 = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
final byte[] usernameHash = new byte[32];
ThreadLocalRandom.current().nextBytes(usernameHash);
final byte[] usernameHash = TestRandomUtil.nextBytes(32);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
@ -186,8 +185,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
final byte[] registrationLockSecret = new byte[32];
ThreadLocalRandom.current().nextBytes(registrationLockSecret);
final byte[] registrationLockSecret = TestRandomUtil.nextBytes(32);
final SetRegistrationLockResponse ignored =
authenticatedServiceStub().setRegistrationLock(SetRegistrationLockRequest.newBuilder()
@ -256,8 +254,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
final byte[] usernameHash = new byte[AccountController.USERNAME_HASH_LENGTH];
ThreadLocalRandom.current().nextBytes(usernameHash);
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
when(accountsManager.reserveUsernameHash(any(), any()))
.thenAnswer(invocation -> {
@ -284,8 +281,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
final byte[] usernameHash = new byte[AccountController.USERNAME_HASH_LENGTH];
ThreadLocalRandom.current().nextBytes(usernameHash);
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
when(accountsManager.reserveUsernameHash(any(), any()))
.thenReturn(CompletableFuture.failedFuture(new UsernameHashNotAvailableException()));
@ -314,9 +310,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final ReserveUsernameHashRequest.Builder requestBuilder = ReserveUsernameHashRequest.newBuilder();
for (int i = 0; i < AccountController.MAXIMUM_USERNAME_HASHES_LIST_LENGTH + 1; i++) {
final byte[] usernameHash = new byte[AccountController.USERNAME_HASH_LENGTH];
ThreadLocalRandom.current().nextBytes(usernameHash);
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
requestBuilder.addUsernameHashes(ByteString.copyFrom(usernameHash));
}
@ -332,8 +326,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
final byte[] usernameHash = new byte[AccountController.USERNAME_HASH_LENGTH + 1];
ThreadLocalRandom.current().nextBytes(usernameHash);
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH + 1);
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
@ -344,8 +337,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Test
void reserveUsernameHashRateLimited() {
final byte[] usernameHash = new byte[AccountController.USERNAME_HASH_LENGTH];
ThreadLocalRandom.current().nextBytes(usernameHash);
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
final Duration retryAfter = Duration.ofMinutes(3);
@ -362,14 +354,11 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Test
void confirmUsernameHash() {
final byte[] usernameHash = new byte[AccountController.USERNAME_HASH_LENGTH];
ThreadLocalRandom.current().nextBytes(usernameHash);
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
final byte[] usernameCiphertext = new byte[32];
ThreadLocalRandom.current().nextBytes(usernameCiphertext);
final byte[] usernameCiphertext = TestRandomUtil.nextBytes(32);
final byte[] zkProof = new byte[32];
ThreadLocalRandom.current().nextBytes(zkProof);
final byte[] zkProof = TestRandomUtil.nextBytes(32);
final UUID linkHandle = UUID.randomUUID();
@ -404,14 +393,11 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@ParameterizedTest
@MethodSource
void confirmUsernameHashConfirmationException(final Exception confirmationException, final Status expectedStatus) {
final byte[] usernameHash = new byte[AccountController.USERNAME_HASH_LENGTH];
ThreadLocalRandom.current().nextBytes(usernameHash);
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
final byte[] usernameCiphertext = new byte[32];
ThreadLocalRandom.current().nextBytes(usernameCiphertext);
final byte[] usernameCiphertext = TestRandomUtil.nextBytes(32);
final byte[] zkProof = new byte[32];
ThreadLocalRandom.current().nextBytes(zkProof);
final byte[] zkProof = TestRandomUtil.nextBytes(32);
final Account account = mock(Account.class);
@ -439,14 +425,11 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Test
void confirmUsernameHashInvalidProof() throws BaseUsernameException {
final byte[] usernameHash = new byte[AccountController.USERNAME_HASH_LENGTH];
ThreadLocalRandom.current().nextBytes(usernameHash);
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
final byte[] usernameCiphertext = new byte[32];
ThreadLocalRandom.current().nextBytes(usernameCiphertext);
final byte[] usernameCiphertext = TestRandomUtil.nextBytes(32);
final byte[] zkProof = new byte[32];
ThreadLocalRandom.current().nextBytes(zkProof);
final byte[] zkProof = TestRandomUtil.nextBytes(32);
final Account account = mock(Account.class);
@ -532,8 +515,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
final byte[] usernameCiphertext = new byte[EncryptedUsername.MAX_SIZE];
ThreadLocalRandom.current().nextBytes(usernameCiphertext);
final byte[] usernameCiphertext = TestRandomUtil.nextBytes(EncryptedUsername.MAX_SIZE);
final SetUsernameLinkResponse response =
authenticatedServiceStub().setUsernameLink(SetUsernameLinkRequest.newBuilder()
@ -561,8 +543,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
final byte[] usernameCiphertext = new byte[EncryptedUsername.MAX_SIZE];
ThreadLocalRandom.current().nextBytes(usernameCiphertext);
final byte[] usernameCiphertext = TestRandomUtil.nextBytes(EncryptedUsername.MAX_SIZE);
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.FAILED_PRECONDITION,
@ -598,8 +579,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(rateLimiter.validateReactive(any(UUID.class)))
.thenReturn(Mono.error(new RateLimitExceededException(retryAfter, false)));
final byte[] usernameCiphertext = new byte[EncryptedUsername.MAX_SIZE];
ThreadLocalRandom.current().nextBytes(usernameCiphertext);
final byte[] usernameCiphertext = TestRandomUtil.nextBytes(EncryptedUsername.MAX_SIZE);
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertRateLimitExceeded(retryAfter,
@ -656,8 +636,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
}
private static Stream<Arguments> configureUnidentifiedAccess() {
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
ThreadLocalRandom.current().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
return Stream.of(
Arguments.of(true, new byte[0], null),
@ -715,8 +694,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
final byte[] registrationRecoveryPassword = new byte[32];
ThreadLocalRandom.current().nextBytes(registrationRecoveryPassword);
final byte[] registrationRecoveryPassword = TestRandomUtil.nextBytes(32);
assertDoesNotThrow(() ->
authenticatedServiceStub().setRegistrationRecoveryPassword(SetRegistrationRecoveryPasswordRequest.newBuilder()

View File

@ -25,7 +25,6 @@ import java.util.Base64;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
import java.util.stream.Stream;
import javax.annotation.Nullable;
@ -55,6 +54,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, DevicesGrpc.DevicesBlockingStub> {
@ -186,8 +186,7 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
final Device device = mock(Device.class);
when(authenticatedAccount.getDevice(deviceId)).thenReturn(Optional.of(device));
final byte[] deviceName = new byte[128];
ThreadLocalRandom.current().nextBytes(deviceName);
final byte[] deviceName = TestRandomUtil.nextBytes(128);
final SetDeviceNameResponse ignored = authenticatedServiceStub().setDeviceName(SetDeviceNameRequest.newBuilder()
.setName(ByteString.copyFrom(deviceName))

View File

@ -12,7 +12,6 @@ import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang3.RandomUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
@ -27,6 +26,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.MutableClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class ExternalServiceCredentialsAnonymousGrpcServiceTest extends
SimpleBaseGrpcTest<ExternalServiceCredentialsAnonymousGrpcService, ExternalServiceCredentialsAnonymousGrpc.ExternalServiceCredentialsAnonymousBlockingStub> {
@ -41,8 +41,8 @@ class ExternalServiceCredentialsAnonymousGrpcServiceTest extends
private static final MutableClock CLOCK = MockUtils.mutableClock(0);
private static final ExternalServiceCredentialsGenerator SVR_CREDENTIALS_GENERATOR = Mockito.spy(ExternalServiceCredentialsGenerator
.builder(RandomUtils.nextBytes(32))
.withUserDerivationKey(RandomUtils.nextBytes(32))
.builder(TestRandomUtil.nextBytes(32))
.withUserDerivationKey(TestRandomUtil.nextBytes(32))
.prependUsername(false)
.withDerivedUsernameTruncateLength(16)
.withClock(CLOCK)

View File

@ -20,7 +20,6 @@ import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
@ -38,20 +37,21 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import reactor.core.publisher.Mono;
public class ExternalServiceCredentialsGrpcServiceTest
extends SimpleBaseGrpcTest<ExternalServiceCredentialsGrpcService, ExternalServiceCredentialsGrpc.ExternalServiceCredentialsBlockingStub> {
private static final ExternalServiceCredentialsGenerator ART_CREDENTIALS_GENERATOR = Mockito.spy(ExternalServiceCredentialsGenerator
.builder(RandomUtils.nextBytes(32))
.withUserDerivationKey(RandomUtils.nextBytes(32))
.builder(TestRandomUtil.nextBytes(32))
.withUserDerivationKey(TestRandomUtil.nextBytes(32))
.prependUsername(false)
.truncateSignature(false)
.build());
private static final ExternalServiceCredentialsGenerator PAYMENTS_CREDENTIALS_GENERATOR = Mockito.spy(ExternalServiceCredentialsGenerator
.builder(RandomUtils.nextBytes(32))
.builder(TestRandomUtil.nextBytes(32))
.prependUsername(true)
.build());

View File

@ -18,7 +18,6 @@ import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
@ -54,6 +53,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
@ -80,8 +80,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final UUID identifier = UUID.randomUUID();
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
when(targetDevice.getId()).thenReturn(Device.PRIMARY_ID);
when(targetDevice.isEnabled()).thenReturn(true);
@ -143,8 +142,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final UUID identifier = UUID.randomUUID();
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
when(targetAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(targetAccount.getUuid()).thenReturn(identifier);
@ -188,8 +186,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
void getPreKeysDeviceNotFound(final byte deviceId) {
final UUID accountIdentifier = UUID.randomUUID();
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final Account targetAccount = mock(Account.class);
when(targetAccount.getUuid()).thenReturn(accountIdentifier);

View File

@ -23,7 +23,6 @@ import io.grpc.Status;
import io.grpc.stub.MetadataUtils;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
@ -78,6 +77,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileAnonymousGrpcService, ProfileAnonymousGrpc.ProfileAnonymousBlockingStub> {
@ -121,8 +121,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final UUID targetUuid = UUID.randomUUID();
final org.whispersystems.textsecuregcm.identity.ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(targetUuid);
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
@ -174,8 +173,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
@ParameterizedTest
@MethodSource
void getUnversionedProfileUnauthenticated(final IdentityType identityType, final boolean missingUnidentifiedAccessKey, final boolean accountNotFound) {
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
@ -210,14 +208,13 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
void getVersionedProfile(final String requestVersion,
@Nullable final String accountVersion,
final boolean expectResponseHasPaymentAddress) {
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final VersionedProfile profile = mock(VersionedProfile.class);
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] emoji = ProfileTestHelper.generateRandomByteArray(60);
final byte[] about = ProfileTestHelper.generateRandomByteArray(156);
final byte[] paymentAddress = ProfileTestHelper.generateRandomByteArray(582);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] emoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final String avatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
when(profile.name()).thenReturn(name);
@ -269,8 +266,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
@Test
void getVersionedProfileVersionNotFound() {
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
@ -296,8 +292,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
@MethodSource
void getVersionedProfileUnauthenticated(final boolean missingUnidentifiedAccessKey,
final boolean accountNotFound) {
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
@ -328,8 +323,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
@Test
void getVersionedProfilePniInvalidArgument() {
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
@ -347,8 +341,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
@Test
void getExpiringProfileKeyCredential() throws InvalidInputException, VerificationFailedException {
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final UUID targetUuid = UUID.randomUUID();
final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
@ -357,9 +350,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final ServerZkProfileOperations serverZkProfile = new ServerZkProfileOperations(serverSecretParams);
final ClientZkProfileOperations clientZkProfile = new ClientZkProfileOperations(serverPublicParams);
final byte[] profileKeyBytes = new byte[32];
new SecureRandom().nextBytes(profileKeyBytes);
final byte[] profileKeyBytes = TestRandomUtil.nextBytes(32);
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(targetUuid));
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
@ -411,8 +402,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
@ParameterizedTest
@MethodSource
void getExpiringProfileKeyCredentialUnauthenticated(final boolean missingAccount, final boolean missingUnidentifiedAccessKey) {
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final UUID targetUuid = UUID.randomUUID();
when(account.getUuid()).thenReturn(targetUuid);
@ -450,8 +440,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
@Test
void getExpiringProfileKeyCredentialProfileNotFound() {
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final UUID targetUuid = UUID.randomUUID();
when(account.getUuid()).thenReturn(targetUuid);
@ -481,8 +470,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
void getExpiringProfileKeyCredentialInvalidArgument(final IdentityType identityType, final CredentialType credentialType,
final boolean throwZkVerificationException) throws VerificationFailedException {
final UUID targetUuid = UUID.randomUUID();
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
if (throwZkVerificationException) {
when(serverZkProfileOperations.issueExpiringProfileKeyCredential(any(), any(), any(), any())).thenThrow(new VerificationFailedException());

View File

@ -28,7 +28,6 @@ import com.google.protobuf.ByteString;
import io.grpc.Metadata;
import io.grpc.Status;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@ -102,6 +101,7 @@ import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.publisher.Mono;
import software.amazon.awssdk.services.s3.S3AsyncClient;
@ -395,8 +395,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid)))
.build())
.build();
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
@ -484,10 +483,10 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
@MethodSource
void getVersionedProfile(final String requestVersion, @Nullable final String accountVersion, final boolean expectResponseHasPaymentAddress) {
final VersionedProfile profile = mock(VersionedProfile.class);
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] emoji = ProfileTestHelper.generateRandomByteArray(60);
final byte[] about = ProfileTestHelper.generateRandomByteArray(156);
final byte[] paymentAddress = ProfileTestHelper.generateRandomByteArray(582);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] emoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final String avatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder()
@ -591,9 +590,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
final ServerZkProfileOperations serverZkProfile = new ServerZkProfileOperations(serverSecretParams);
final ClientZkProfileOperations clientZkProfile = new ClientZkProfileOperations(serverPublicParams);
final byte[] profileKeyBytes = new byte[32];
new SecureRandom().nextBytes(profileKeyBytes);
final byte[] profileKeyBytes = TestRandomUtil.nextBytes(32);
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(targetUuid));
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =

View File

@ -20,7 +20,6 @@ import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
@ -40,6 +39,7 @@ import org.signal.chat.rpc.ValidationTestServiceGrpc;
import org.signal.chat.rpc.ValidationsRequest;
import org.signal.chat.rpc.ValidationsResponse;
import org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import reactor.core.publisher.Mono;
public class ValidatingInterceptorTest {
@ -107,7 +107,7 @@ public class ValidatingInterceptorTest {
.build()
));
final ByteString byteValue = ByteString.copyFrom(RandomUtils.nextBytes(size));
final ByteString byteValue = ByteString.copyFrom(TestRandomUtil.nextBytes(size));
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(
builderWithValidDefaults()
.setFixedSizeBytes(byteValue)
@ -184,7 +184,7 @@ public class ValidatingInterceptorTest {
.build()
)).getCode());
final ByteString byteValue = ByteString.copyFrom(RandomUtils.nextBytes(size));
final ByteString byteValue = ByteString.copyFrom(TestRandomUtil.nextBytes(size));
assertEquals(expectedStatus.getCode(), requestStatus(() -> stub.validationsEndpoint(
builderWithValidDefaults()
.setRangeSizeBytes(byteValue)

View File

@ -9,7 +9,6 @@ import static org.mockito.Mockito.verify;
import com.google.protobuf.ByteString;
import java.time.Duration;
import java.util.Random;
import java.util.function.Consumer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@ -19,6 +18,7 @@ import org.mockito.ArgumentCaptor;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.redis.RedisSingletonExtension;
import org.whispersystems.textsecuregcm.storage.PubSubProtos;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.websocket.ProvisioningAddress;
class ProvisioningManagerTest {
@ -45,8 +45,7 @@ class ProvisioningManagerTest {
void sendProvisioningMessage() {
final ProvisioningAddress address = ProvisioningAddress.create("address");
final byte[] content = new byte[16];
new Random().nextBytes(content);
final byte[] content = TestRandomUtil.nextBytes(16);
@SuppressWarnings("unchecked") final Consumer<PubSubProtos.PubSubMessage> subscribedConsumer = mock(Consumer.class);
@ -66,8 +65,7 @@ class ProvisioningManagerTest {
void removeListener() {
final ProvisioningAddress address = ProvisioningAddress.create("address");
final byte[] content = new byte[16];
new Random().nextBytes(content);
final byte[] content = TestRandomUtil.nextBytes(16);
@SuppressWarnings("unchecked") final Consumer<PubSubProtos.PubSubMessage> subscribedConsumer = mock(Consumer.class);

View File

@ -18,7 +18,6 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@ -34,7 +33,6 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import org.apache.commons.lang3.RandomUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
@ -49,6 +47,7 @@ import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
@ -196,8 +195,7 @@ class AccountsManagerUsernameIntegrationTest {
}
byte[] availableHash = new byte[32];
new SecureRandom().nextBytes(availableHash);
byte[] availableHash = TestRandomUtil.nextBytes(32);
usernameHashes.add(availableHash);
// first time this is called lie and say the username is available
@ -313,11 +311,11 @@ class AccountsManagerUsernameIntegrationTest {
public void testUsernameLinks() throws InterruptedException {
final Account account = AccountsHelper.createAccount(accountsManager, "+18005551111");
account.setUsernameHash(RandomUtils.nextBytes(16));
account.setUsernameHash(TestRandomUtil.nextBytes(16));
accounts.create(account, ignored -> Collections.emptyList());
final UUID linkHandle = UUID.randomUUID();
final byte[] encryptedUsername = RandomUtils.nextBytes(32);
final byte[] encryptedUsername = TestRandomUtil.nextBytes(32);
accountsManager.update(account, a -> a.setUsernameLinkDetails(linkHandle, encryptedUsername));
final Optional<Account> maybeAccount = accountsManager.getByUsernameLinkHandle(linkHandle).join();

View File

@ -39,7 +39,6 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
@ -59,6 +58,7 @@ import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import reactor.core.scheduler.Schedulers;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@ -128,7 +128,7 @@ class AccountsTest {
@Test
public void testStoreAndLookupUsernameLink() {
final Account account = nextRandomAccount();
account.setUsernameHash(RandomUtils.nextBytes(16));
account.setUsernameHash(TestRandomUtil.nextBytes(16));
createAccount(account);
final BiConsumer<Optional<Account>, byte[]> validator = (maybeAccount, expectedEncryptedUsername) -> {
@ -140,14 +140,14 @@ class AccountsTest {
// creating a username link, storing it, checking that it can be looked up
final UUID linkHandle1 = UUID.randomUUID();
final byte[] encruptedUsername1 = RandomUtils.nextBytes(32);
final byte[] encruptedUsername1 = TestRandomUtil.nextBytes(32);
account.setUsernameLinkDetails(linkHandle1, encruptedUsername1);
accounts.update(account);
validator.accept(accounts.getByUsernameLinkHandle(linkHandle1).join(), encruptedUsername1);
// updating username link, storing new one, checking that it can be looked up, checking that old one can't be looked up
final UUID linkHandle2 = UUID.randomUUID();
final byte[] encruptedUsername2 = RandomUtils.nextBytes(32);
final byte[] encruptedUsername2 = TestRandomUtil.nextBytes(32);
account.setUsernameLinkDetails(linkHandle2, encruptedUsername2);
accounts.update(account);
validator.accept(accounts.getByUsernameLinkHandle(linkHandle2).join(), encruptedUsername2);
@ -1037,8 +1037,8 @@ class AccountsTest {
@Test
public void testIgnoredFieldsNotAddedToDataAttribute() throws Exception {
final Account account = generateAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID());
account.setUsernameHash(RandomUtils.nextBytes(32));
account.setUsernameLinkDetails(UUID.randomUUID(), RandomUtils.nextBytes(32));
account.setUsernameHash(TestRandomUtil.nextBytes(32));
account.setUsernameLinkDetails(UUID.randomUUID(), TestRandomUtil.nextBytes(32));
createAccount(account);
final Map<String, AttributeValue> accountRecord = DYNAMO_DB_EXTENSION.getDynamoDbClient()
.getItem(GetItemRequest.builder()

View File

@ -9,7 +9,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
@ -19,13 +18,13 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessor;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessor;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class IssuedReceiptsManagerTest {
private static final long NOW_EPOCH_SECONDS = 1_500_000_000L;
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
@RegisterExtension
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.ISSUED_RECEIPTS);
@ -36,20 +35,17 @@ class IssuedReceiptsManagerTest {
@BeforeEach
void beforeEach() {
receiptCredentialRequest = mock(ReceiptCredentialRequest.class);
byte[] generator = new byte[16];
SECURE_RANDOM.nextBytes(generator);
issuedReceiptsManager = new IssuedReceiptsManager(
Tables.ISSUED_RECEIPTS.tableName(),
Duration.ofDays(90),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
generator);
TestRandomUtil.nextBytes(16));
}
@Test
void testRecordIssuance() {
Instant now = Instant.ofEpochSecond(NOW_EPOCH_SECONDS);
byte[] request1 = new byte[20];
SECURE_RANDOM.nextBytes(request1);
byte[] request1 = TestRandomUtil.nextBytes(20);
when(receiptCredentialRequest.serialize()).thenReturn(request1);
CompletableFuture<Void> future = issuedReceiptsManager.recordIssuance("item-1", SubscriptionProcessor.STRIPE,
receiptCredentialRequest, now);
@ -61,8 +57,7 @@ class IssuedReceiptsManagerTest {
assertThat(future).succeedsWithin(Duration.ofSeconds(3));
// same item with new request should fail
byte[] request2 = new byte[20];
SECURE_RANDOM.nextBytes(request2);
byte[] request2 = TestRandomUtil.nextBytes(20);
when(receiptCredentialRequest.serialize()).thenReturn(request2);
future = issuedReceiptsManager.recordIssuance("item-1", SubscriptionProcessor.STRIPE, receiptCredentialRequest,
now);

View File

@ -34,6 +34,7 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.tests.util.MockRedisFuture;
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public class ProfilesManagerTest {
@ -62,7 +63,7 @@ public class ProfilesManagerTest {
@Test
public void testGetProfileInCache() throws InvalidInputException {
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
when(commands.hget(eq("profiles::" + uuid), eq("someversion"))).thenReturn(String.format(
"{\"version\": \"someversion\", \"name\": \"%s\", \"avatar\": \"someavatar\", \"commitment\":\"%s\"}",
@ -84,7 +85,7 @@ public class ProfilesManagerTest {
@Test
public void testGetProfileAsyncInCache() throws InvalidInputException {
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
when(asyncCommands.hget(eq("profiles::" + uuid), eq("someversion"))).thenReturn(
@ -107,7 +108,7 @@ public class ProfilesManagerTest {
@Test
public void testGetProfileNotInCache() {
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, "somecommitment".getBytes());
@ -130,7 +131,7 @@ public class ProfilesManagerTest {
@Test
public void testGetProfileAsyncNotInCache() {
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, "somecommitment".getBytes());
@ -154,7 +155,7 @@ public class ProfilesManagerTest {
@Test
public void testGetProfileBrokenCache() {
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, "somecommitment".getBytes());
@ -177,7 +178,7 @@ public class ProfilesManagerTest {
@Test
public void testGetProfileAsyncBrokenCache() {
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, "somecommitment".getBytes());
@ -201,7 +202,7 @@ public class ProfilesManagerTest {
@Test
public void testSet() {
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, "somecommitment".getBytes());
@ -217,7 +218,7 @@ public class ProfilesManagerTest {
@Test
public void testSetAsync() {
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, "somecommitment".getBytes());

View File

@ -5,6 +5,13 @@
package org.whispersystems.textsecuregcm.storage;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
@ -15,19 +22,12 @@ import org.junit.jupiter.params.provider.MethodSource;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Stream;
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public class ProfilesTest {
private static final UUID ACI = UUID.randomUUID();
@ -44,9 +44,9 @@ public class ProfilesTest {
Tables.PROFILES.tableName());
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(ACI)).serialize();
final String version = "someVersion";
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] validAboutEmoji = ProfileTestHelper.generateRandomByteArray(60);
final byte[] validAbout = ProfileTestHelper.generateRandomByteArray(156);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] validAboutEmoji = TestRandomUtil.nextBytes(60);
final byte[] validAbout = TestRandomUtil.nextBytes(156);
final String avatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
validProfile = new VersionedProfile(version, name, avatar, validAboutEmoji, validAbout, null, commitment);
@ -87,12 +87,12 @@ public class ProfilesTest {
profiles.deleteAll(ACI).join();
final String version = "someVersion";
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
final String differentAvatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
final byte[] differentEmoji = ProfileTestHelper.generateRandomByteArray(60);
final byte[] differentAbout = ProfileTestHelper.generateRandomByteArray(156);
final byte[] paymentAddress = ProfileTestHelper.generateRandomByteArray(582);
final byte[] commitment = new ProfileKey(ProfileTestHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] differentEmoji = TestRandomUtil.nextBytes(60);
final byte[] differentAbout = TestRandomUtil.nextBytes(156);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] commitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile updatedProfile = new VersionedProfile(version, name, differentAvatar,
differentEmoji, differentAbout, paymentAddress, commitment);
@ -112,8 +112,8 @@ public class ProfilesTest {
@Test
void testSetGetNullOptionalFields() throws InvalidInputException {
final String version = "someVersion";
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] commitment = new ProfileKey(ProfileTestHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] commitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile profile = new VersionedProfile(version, name, null, null, null, null,
commitment);
@ -143,11 +143,11 @@ public class ProfilesTest {
assertThat(retrieved.get().aboutEmoji()).isEqualTo(validProfile.aboutEmoji());
assertThat(retrieved.get().paymentAddress()).isNull();
final byte[] differentName = ProfileTestHelper.generateRandomByteArray(81);
final byte[] differentEmoji = ProfileTestHelper.generateRandomByteArray(60);
final byte[] differentAbout = ProfileTestHelper.generateRandomByteArray(156);
final byte[] differentName = TestRandomUtil.nextBytes(81);
final byte[] differentEmoji = TestRandomUtil.nextBytes(60);
final byte[] differentAbout = TestRandomUtil.nextBytes(156);
final String differentAvatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
final byte[] differentCommitment = new ProfileKey(ProfileTestHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] differentCommitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile updated = new VersionedProfile(validProfile.version(), differentName, differentAvatar, differentEmoji, differentAbout, null,
differentCommitment);
@ -170,17 +170,17 @@ public class ProfilesTest {
final String versionOne = "versionOne";
final String versionTwo = "versionTwo";
final byte[] nameOne = ProfileTestHelper.generateRandomByteArray(81);
final byte[] nameTwo = ProfileTestHelper.generateRandomByteArray(81);
final byte[] nameOne = TestRandomUtil.nextBytes(81);
final byte[] nameTwo = TestRandomUtil.nextBytes(81);
final String avatarOne = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
final String avatarTwo = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
final byte[] aboutEmoji = ProfileTestHelper.generateRandomByteArray(60);
final byte[] about = ProfileTestHelper.generateRandomByteArray(156);
final byte[] aboutEmoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
final byte[] commitmentOne = new ProfileKey(ProfileTestHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentTwo = new ProfileKey(ProfileTestHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentOne = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentTwo = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile profileOne = new VersionedProfile(versionOne, nameOne, avatarOne, null, null,
null, commitmentOne);
@ -223,17 +223,17 @@ public class ProfilesTest {
final String versionOne = "versionOne";
final String versionTwo = "versionTwo";
final byte[] nameOne = ProfileTestHelper.generateRandomByteArray(81);
final byte[] nameTwo = ProfileTestHelper.generateRandomByteArray(81);
final byte[] nameOne = TestRandomUtil.nextBytes(81);
final byte[] nameTwo = TestRandomUtil.nextBytes(81);
final byte[] aboutEmoji = ProfileTestHelper.generateRandomByteArray(60);
final byte[] about = ProfileTestHelper.generateRandomByteArray(156);
final byte[] aboutEmoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
final String avatarOne = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
final String avatarTwo = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
final byte[] commitmentOne = new ProfileKey(ProfileTestHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentTwo = new ProfileKey(ProfileTestHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentOne = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentTwo = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile profileOne = new VersionedProfile(versionOne, nameOne, avatarOne, null, null,
null, commitmentOne);
@ -261,12 +261,12 @@ public class ProfilesTest {
private static Stream<Arguments> buildUpdateExpression() throws InvalidInputException {
final String version = "someVersion";
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
final String avatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);;
final byte[] emoji = ProfileTestHelper.generateRandomByteArray(60);
final byte[] about = ProfileTestHelper.generateRandomByteArray(156);
final byte[] paymentAddress = ProfileTestHelper.generateRandomByteArray(582);
final byte[] commitment = new ProfileKey(ProfileTestHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] emoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] commitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
return Stream.of(
Arguments.of(
@ -303,12 +303,12 @@ public class ProfilesTest {
private static Stream<Arguments> buildUpdateExpressionAttributeValues() throws InvalidInputException {
final String version = "someVersion";
final byte[] name = ProfileTestHelper.generateRandomByteArray(81);
final byte[] name = TestRandomUtil.nextBytes(81);
final String avatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);;
final byte[] emoji = ProfileTestHelper.generateRandomByteArray(60);
final byte[] about = ProfileTestHelper.generateRandomByteArray(156);
final byte[] paymentAddress = ProfileTestHelper.generateRandomByteArray(582);
final byte[] commitment = new ProfileKey(ProfileTestHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] emoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] commitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
return Stream.of(
Arguments.of(

View File

@ -19,6 +19,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class PushChallengeDynamoDbTest {
@ -66,9 +67,6 @@ class PushChallengeDynamoDbTest {
}
private static byte[] generateRandomToken() {
final byte[] token = new byte[16];
RANDOM.nextBytes(token);
return token;
return TestRandomUtil.nextBytes(16);
}
}

View File

@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.storage;
import static org.assertj.core.api.Assertions.assertThat;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@ -21,11 +20,11 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class RedeemedReceiptsManagerTest {
private static final long NOW_EPOCH_SECONDS = 1_500_000_000L;
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
@RegisterExtension
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.REDEEMED_RECEIPTS);
@ -36,9 +35,7 @@ class RedeemedReceiptsManagerTest {
@BeforeEach
void beforeEach() throws InvalidInputException {
byte[] receiptSerialBytes = new byte[ReceiptSerial.SIZE];
SECURE_RANDOM.nextBytes(receiptSerialBytes);
receiptSerial = new ReceiptSerial(receiptSerialBytes);
receiptSerial = new ReceiptSerial(TestRandomUtil.nextBytes(ReceiptSerial.SIZE));
redeemedReceiptsManager = new RedeemedReceiptsManager(
clock,
Tables.REDEEMED_RECEIPTS.tableName(),

View File

@ -24,11 +24,12 @@ import org.assertj.core.api.Condition;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager.GetResult;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager.Record;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessor;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class SubscriptionManagerTest {
@ -47,9 +48,9 @@ class SubscriptionManagerTest {
@BeforeEach
void beforeEach() {
user = getRandomBytes(16);
password = getRandomBytes(16);
customer = Base64.getEncoder().encodeToString(getRandomBytes(16));
user = TestRandomUtil.nextBytes(16);
password = TestRandomUtil.nextBytes(16);
customer = Base64.getEncoder().encodeToString(TestRandomUtil.nextBytes(16));
created = Instant.ofEpochSecond(NOW_EPOCH_SECONDS);
subscriptionManager = new SubscriptionManager(
Tables.SUBSCRIPTIONS.tableName(), DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient());
@ -57,8 +58,8 @@ class SubscriptionManagerTest {
@Test
void testCreateOnlyOnce() {
byte[] password1 = getRandomBytes(16);
byte[] password2 = getRandomBytes(16);
byte[] password1 = TestRandomUtil.nextBytes(16);
byte[] password2 = TestRandomUtil.nextBytes(16);
Instant created1 = Instant.ofEpochSecond(NOW_EPOCH_SECONDS);
Instant created2 = Instant.ofEpochSecond(NOW_EPOCH_SECONDS + 1);
@ -90,8 +91,8 @@ class SubscriptionManagerTest {
@Test
void testGet() {
byte[] wrongUser = getRandomBytes(16);
byte[] wrongPassword = getRandomBytes(16);
byte[] wrongUser = TestRandomUtil.nextBytes(16);
byte[] wrongPassword = TestRandomUtil.nextBytes(16);
assertThat(subscriptionManager.create(user, password, created)).succeedsWithin(DEFAULT_TIMEOUT);
assertThat(subscriptionManager.get(user, password)).succeedsWithin(DEFAULT_TIMEOUT).satisfies(getResult -> {
@ -192,7 +193,7 @@ class SubscriptionManagerTest {
@Test
void testSubscriptionCreated() {
String subscriptionId = Base64.getEncoder().encodeToString(getRandomBytes(16));
String subscriptionId = Base64.getEncoder().encodeToString(TestRandomUtil.nextBytes(16));
Instant subscriptionCreated = Instant.ofEpochSecond(NOW_EPOCH_SECONDS + 1);
long level = 42;
assertThat(subscriptionManager.create(user, password, created)).succeedsWithin(DEFAULT_TIMEOUT);
@ -241,12 +242,6 @@ class SubscriptionManagerTest {
assertThat(processorCustomer.toDynamoBytes()).isEqualTo(new byte[]{1, 97, 98, 99});
}
private static byte[] getRandomBytes(int length) {
byte[] result = new byte[length];
SECURE_RANDOM.nextBytes(result);
return result;
}
@Nonnull
private static Consumer<Record> checkFreshlyCreatedRecord(
byte[] user, byte[] password, Instant created) {

View File

@ -1,17 +1,11 @@
package org.whispersystems.textsecuregcm.tests.util;
import java.util.Base64;
import java.util.Random;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
public class ProfileTestHelper {
public static String generateRandomBase64FromByteArray(final int byteArrayLength) {
return encodeToBase64(generateRandomByteArray(byteArrayLength));
}
public static byte[] generateRandomByteArray(final int length) {
byte[] byteArray = new byte[length];
new Random().nextBytes(byteArray);
return byteArray;
return encodeToBase64(TestRandomUtil.nextBytes(byteArrayLength));
}
public static String encodeToBase64(final byte[] input) {

View File

@ -20,8 +20,6 @@ import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import org.apache.commons.lang3.RandomUtils;
import org.mockito.Mockito;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.MatchableInvocation;
@ -155,7 +153,7 @@ public final class MockUtils {
}
public static SecretBytes randomSecretBytes(final int size) {
return new SecretBytes(RandomUtils.nextBytes(size));
return new SecretBytes(TestRandomUtil.nextBytes(size));
}
public static SecretBytes secretBytesOf(final int... byteVals) {

View File

@ -0,0 +1,13 @@
package org.whispersystems.textsecuregcm.util;
import java.util.concurrent.ThreadLocalRandom;
public class TestRandomUtil {
private TestRandomUtil() {}
public static byte[] nextBytes(int numBytes) {
final byte[] bytes = new byte[numBytes];
ThreadLocalRandom.current().nextBytes(bytes);
return bytes;
}
}