Merge branch 'tests-cleanup' into 'master'

Clean up tests

* Broke up ConstantsTest (#280) - the key encoding parts are now in KeyEncodingAndParsingTest, the message encoding parts are in MessageSizeIntegrationTest
* Renamed the other integration tests in briar-android-tests
* Moved the integration tests in briar-android-tests to the top-level package, as they all involve code from multiple packages
* Separated DatabaseExecutorModule from DatabaseModule so we can use a different @DatabaseExecutor in integration tests
* Merged AppModule with AndroidModule (@ernir, this touches code you're working on but I don't think there are any conflicts)
* Renamed some TestUtils methods for consistency
* Used TestUtils.getRandomBytes() where applicable

Fixes #280.

See merge request !133
This commit is contained in:
akwizgran
2016-04-06 16:03:48 +00:00
42 changed files with 532 additions and 581 deletions

View File

@@ -1,12 +1,8 @@
package org.briarproject.sync; package org.briarproject;
import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.api.UniqueId; import org.briarproject.api.UniqueId;
import org.briarproject.api.crypto.CryptoComponent; import org.briarproject.api.crypto.CryptoComponent;
import org.briarproject.api.crypto.KeyPair;
import org.briarproject.api.crypto.PrivateKey; import org.briarproject.api.crypto.PrivateKey;
import org.briarproject.api.crypto.Signature;
import org.briarproject.api.forum.ForumConstants; import org.briarproject.api.forum.ForumConstants;
import org.briarproject.api.forum.ForumPost; import org.briarproject.api.forum.ForumPost;
import org.briarproject.api.forum.ForumPostFactory; import org.briarproject.api.forum.ForumPostFactory;
@@ -15,25 +11,21 @@ import org.briarproject.api.identity.AuthorFactory;
import org.briarproject.api.messaging.MessagingConstants; import org.briarproject.api.messaging.MessagingConstants;
import org.briarproject.api.messaging.PrivateMessage; import org.briarproject.api.messaging.PrivateMessage;
import org.briarproject.api.messaging.PrivateMessageFactory; import org.briarproject.api.messaging.PrivateMessageFactory;
import static org.briarproject.api.forum.ForumConstants.MAX_FORUM_POST_BODY_LENGTH;
import static org.briarproject.api.identity.AuthorConstants.MAX_AUTHOR_NAME_LENGTH;
import static org.briarproject.api.identity.AuthorConstants.MAX_PUBLIC_KEY_LENGTH;
import static org.briarproject.api.identity.AuthorConstants.MAX_SIGNATURE_LENGTH;
import static org.briarproject.api.messaging.MessagingConstants.MAX_PRIVATE_MESSAGE_BODY_LENGTH;
import static org.briarproject.api.sync.SyncConstants.MAX_PACKET_PAYLOAD_LENGTH;
import static org.junit.Assert.assertTrue;
import org.briarproject.api.sync.GroupId; import org.briarproject.api.sync.GroupId;
import org.briarproject.api.sync.MessageId; import org.briarproject.api.sync.MessageId;
import org.junit.Test; import org.junit.Test;
import java.util.Random;
import javax.inject.Inject; import javax.inject.Inject;
public class ConstantsTest extends BriarTestCase { import static org.briarproject.api.forum.ForumConstants.MAX_FORUM_POST_BODY_LENGTH;
import static org.briarproject.api.identity.AuthorConstants.MAX_AUTHOR_NAME_LENGTH;
import static org.briarproject.api.identity.AuthorConstants.MAX_PUBLIC_KEY_LENGTH;
import static org.briarproject.api.messaging.MessagingConstants.MAX_PRIVATE_MESSAGE_BODY_LENGTH;
import static org.briarproject.api.sync.SyncConstants.MAX_PACKET_PAYLOAD_LENGTH;
import static org.junit.Assert.assertTrue;
public class MessageSizeIntegrationTest extends BriarTestCase {
// TODO: Break this up into tests that are relevant for each package
@Inject @Inject
CryptoComponent crypto; CryptoComponent crypto;
@Inject @Inject
@@ -43,52 +35,19 @@ public class ConstantsTest extends BriarTestCase {
@Inject @Inject
ForumPostFactory forumPostFactory; ForumPostFactory forumPostFactory;
private final ConstantsComponent component; public MessageSizeIntegrationTest() throws Exception {
MessageSizeIntegrationTestComponent component =
public ConstantsTest() throws Exception { DaggerMessageSizeIntegrationTestComponent.builder().build();
component = DaggerConstantsComponent.builder().build();
component.inject(this); component.inject(this);
} }
@Test
public void testAgreementPublicKeys() throws Exception {
// Generate 10 agreement key pairs
for (int i = 0; i < 10; i++) {
KeyPair keyPair = crypto.generateSignatureKeyPair();
// Check the length of the public key
byte[] publicKey = keyPair.getPublic().getEncoded();
assertTrue(publicKey.length <= MAX_PUBLIC_KEY_LENGTH);
}
}
@Test
public void testSignaturePublicKeys() throws Exception {
Random random = new Random();
Signature sig = crypto.getSignature();
// Generate 10 signature key pairs
for (int i = 0; i < 10; i++) {
KeyPair keyPair = crypto.generateSignatureKeyPair();
// Check the length of the public key
byte[] publicKey = keyPair.getPublic().getEncoded();
assertTrue(publicKey.length <= MAX_PUBLIC_KEY_LENGTH);
// Sign some random data and check the length of the signature
byte[] toBeSigned = new byte[1234];
random.nextBytes(toBeSigned);
sig.initSign(keyPair.getPrivate());
sig.update(toBeSigned);
byte[] signature = sig.sign();
assertTrue(signature.length <= MAX_SIGNATURE_LENGTH);
}
}
@Test @Test
public void testPrivateMessageFitsIntoPacket() throws Exception { public void testPrivateMessageFitsIntoPacket() throws Exception {
// Create a maximum-length private message // Create a maximum-length private message
GroupId groupId = new GroupId(TestUtils.getRandomId()); GroupId groupId = new GroupId(TestUtils.getRandomId());
long timestamp = Long.MAX_VALUE; long timestamp = Long.MAX_VALUE;
MessageId parent = new MessageId(TestUtils.getRandomId()); MessageId parent = new MessageId(TestUtils.getRandomId());
String contentType = TestUtils.createRandomString( String contentType = TestUtils.getRandomString(
MessagingConstants.MAX_CONTENT_TYPE_LENGTH); MessagingConstants.MAX_CONTENT_TYPE_LENGTH);
byte[] body = new byte[MAX_PRIVATE_MESSAGE_BODY_LENGTH]; byte[] body = new byte[MAX_PRIVATE_MESSAGE_BODY_LENGTH];
PrivateMessage message = privateMessageFactory.createPrivateMessage( PrivateMessage message = privateMessageFactory.createPrivateMessage(
@@ -104,7 +63,7 @@ public class ConstantsTest extends BriarTestCase {
@Test @Test
public void testForumPostFitsIntoPacket() throws Exception { public void testForumPostFitsIntoPacket() throws Exception {
// Create a maximum-length author // Create a maximum-length author
String authorName = TestUtils.createRandomString( String authorName = TestUtils.getRandomString(
MAX_AUTHOR_NAME_LENGTH); MAX_AUTHOR_NAME_LENGTH);
byte[] authorPublic = new byte[MAX_PUBLIC_KEY_LENGTH]; byte[] authorPublic = new byte[MAX_PUBLIC_KEY_LENGTH];
Author author = authorFactory.createAuthor(authorName, authorPublic); Author author = authorFactory.createAuthor(authorName, authorPublic);
@@ -112,7 +71,7 @@ public class ConstantsTest extends BriarTestCase {
GroupId groupId = new GroupId(TestUtils.getRandomId()); GroupId groupId = new GroupId(TestUtils.getRandomId());
long timestamp = Long.MAX_VALUE; long timestamp = Long.MAX_VALUE;
MessageId parent = new MessageId(TestUtils.getRandomId()); MessageId parent = new MessageId(TestUtils.getRandomId());
String contentType = TestUtils.createRandomString( String contentType = TestUtils.getRandomString(
ForumConstants.MAX_CONTENT_TYPE_LENGTH); ForumConstants.MAX_CONTENT_TYPE_LENGTH);
byte[] body = new byte[MAX_FORUM_POST_BODY_LENGTH]; byte[] body = new byte[MAX_FORUM_POST_BODY_LENGTH];
PrivateKey privateKey = crypto.generateSignatureKeyPair().getPrivate(); PrivateKey privateKey = crypto.generateSignatureKeyPair().getPrivate();

View File

@@ -0,0 +1,34 @@
package org.briarproject;
import org.briarproject.clients.ClientsModule;
import org.briarproject.crypto.CryptoModule;
import org.briarproject.data.DataModule;
import org.briarproject.db.DatabaseModule;
import org.briarproject.event.EventModule;
import org.briarproject.forum.ForumModule;
import org.briarproject.identity.IdentityModule;
import org.briarproject.messaging.MessagingModule;
import org.briarproject.sync.SyncModule;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {
TestDatabaseModule.class,
TestLifecycleModule.class,
TestSystemModule.class,
ClientsModule.class,
CryptoModule.class,
DataModule.class,
DatabaseModule.class,
EventModule.class,
ForumModule.class,
IdentityModule.class,
MessagingModule.class,
SyncModule.class
})
public interface MessageSizeIntegrationTestComponent {
void inject(MessageSizeIntegrationTest testCase);
}

View File

@@ -1,15 +1,9 @@
package org.briarproject.sync; package org.briarproject;
import org.briarproject.BriarTestCase;
import org.briarproject.ImmediateExecutor;
import org.briarproject.TestDatabaseModule;
import org.briarproject.TestUtils;
import org.briarproject.api.contact.ContactId; import org.briarproject.api.contact.ContactId;
import org.briarproject.api.contact.ContactManager; import org.briarproject.api.contact.ContactManager;
import org.briarproject.api.crypto.SecretKey; import org.briarproject.api.crypto.SecretKey;
import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.event.Event; import org.briarproject.api.event.Event;
import org.briarproject.api.event.EventBus;
import org.briarproject.api.event.EventListener; import org.briarproject.api.event.EventListener;
import org.briarproject.api.event.MessageAddedEvent; import org.briarproject.api.event.MessageAddedEvent;
import org.briarproject.api.identity.Author; import org.briarproject.api.identity.Author;
@@ -21,11 +15,8 @@ import org.briarproject.api.messaging.MessagingManager;
import org.briarproject.api.messaging.PrivateMessage; import org.briarproject.api.messaging.PrivateMessage;
import org.briarproject.api.messaging.PrivateMessageFactory; import org.briarproject.api.messaging.PrivateMessageFactory;
import org.briarproject.api.sync.GroupId; import org.briarproject.api.sync.GroupId;
import org.briarproject.api.sync.PacketReader;
import org.briarproject.api.sync.PacketReaderFactory;
import org.briarproject.api.sync.PacketWriter;
import org.briarproject.api.sync.PacketWriterFactory;
import org.briarproject.api.sync.SyncSession; import org.briarproject.api.sync.SyncSession;
import org.briarproject.api.sync.SyncSessionFactory;
import org.briarproject.api.transport.KeyManager; import org.briarproject.api.transport.KeyManager;
import org.briarproject.api.transport.StreamContext; import org.briarproject.api.transport.StreamContext;
import org.briarproject.api.transport.StreamReaderFactory; import org.briarproject.api.transport.StreamReaderFactory;
@@ -54,19 +45,19 @@ public class SimplexMessagingIntegrationTest extends BriarTestCase {
private final File testDir = TestUtils.getTestDirectory(); private final File testDir = TestUtils.getTestDirectory();
private final File aliceDir = new File(testDir, "alice"); private final File aliceDir = new File(testDir, "alice");
private final File bobDir = new File(testDir, "bob"); private final File bobDir = new File(testDir, "bob");
private final SecretKey master = TestUtils.createSecretKey(); private final SecretKey master = TestUtils.getSecretKey();
private final long timestamp = System.currentTimeMillis(); private final long timestamp = System.currentTimeMillis();
private final AuthorId aliceId = new AuthorId(TestUtils.getRandomId()); private final AuthorId aliceId = new AuthorId(TestUtils.getRandomId());
private final AuthorId bobId = new AuthorId(TestUtils.getRandomId()); private final AuthorId bobId = new AuthorId(TestUtils.getRandomId());
private SimplexMessagingComponent alice, bob; private SimplexMessagingIntegrationTestComponent alice, bob;
@Before @Before
public void setUp() { public void setUp() {
assertTrue(testDir.mkdirs()); assertTrue(testDir.mkdirs());
alice = DaggerSimplexMessagingComponent.builder() alice = DaggerSimplexMessagingIntegrationTestComponent.builder()
.testDatabaseModule(new TestDatabaseModule(aliceDir)).build(); .testDatabaseModule(new TestDatabaseModule(aliceDir)).build();
bob = DaggerSimplexMessagingComponent.builder() bob = DaggerSimplexMessagingIntegrationTestComponent.builder()
.testDatabaseModule(new TestDatabaseModule(bobDir)).build(); .testDatabaseModule(new TestDatabaseModule(bobDir)).build();
} }
@@ -78,18 +69,15 @@ public class SimplexMessagingIntegrationTest extends BriarTestCase {
private byte[] write() throws Exception { private byte[] write() throws Exception {
// Instantiate Alice's services // Instantiate Alice's services
LifecycleManager lifecycleManager = alice.getLifecycleManager(); LifecycleManager lifecycleManager = alice.getLifecycleManager();
DatabaseComponent db = alice.getDatabaseComponent();
IdentityManager identityManager = alice.getIdentityManager(); IdentityManager identityManager = alice.getIdentityManager();
ContactManager contactManager = alice.getContactManager(); ContactManager contactManager = alice.getContactManager();
MessagingManager messagingManager = alice.getMessagingManager(); MessagingManager messagingManager = alice.getMessagingManager();
KeyManager keyManager = alice.getKeyManager(); KeyManager keyManager = alice.getKeyManager();
PrivateMessageFactory privateMessageFactory = PrivateMessageFactory privateMessageFactory =
alice.getPrivateMessageFactory(); alice.getPrivateMessageFactory();
PacketWriterFactory packetWriterFactory =
alice.getPacketWriterFactory();
EventBus eventBus = alice.getEventBus();
StreamWriterFactory streamWriterFactory = StreamWriterFactory streamWriterFactory =
alice.getStreamWriterFactory(); alice.getStreamWriterFactory();
SyncSessionFactory syncSessionFactory = alice.getSyncSessionFactory();
// Start the lifecycle manager // Start the lifecycle manager
lifecycleManager.startServices(); lifecycleManager.startServices();
@@ -119,11 +107,8 @@ public class SimplexMessagingIntegrationTest extends BriarTestCase {
OutputStream streamWriter = streamWriterFactory.createStreamWriter( OutputStream streamWriter = streamWriterFactory.createStreamWriter(
out, ctx); out, ctx);
// Create an outgoing sync session // Create an outgoing sync session
PacketWriter packetWriter = packetWriterFactory.createPacketWriter( SyncSession session = syncSessionFactory.createSimplexOutgoingSession(
streamWriter); contactId, MAX_LATENCY, streamWriter);
SyncSession session = new SimplexOutgoingSession(db,
new ImmediateExecutor(), eventBus, contactId, MAX_LATENCY,
packetWriter);
// Write whatever needs to be written // Write whatever needs to be written
session.run(); session.run();
streamWriter.close(); streamWriter.close();
@@ -139,13 +124,11 @@ public class SimplexMessagingIntegrationTest extends BriarTestCase {
private void read(byte[] stream) throws Exception { private void read(byte[] stream) throws Exception {
// Instantiate Bob's services // Instantiate Bob's services
LifecycleManager lifecycleManager = bob.getLifecycleManager(); LifecycleManager lifecycleManager = bob.getLifecycleManager();
DatabaseComponent db = bob.getDatabaseComponent();
IdentityManager identityManager = bob.getIdentityManager(); IdentityManager identityManager = bob.getIdentityManager();
ContactManager contactManager = bob.getContactManager(); ContactManager contactManager = bob.getContactManager();
KeyManager keyManager = bob.getKeyManager(); KeyManager keyManager = bob.getKeyManager();
StreamReaderFactory streamReaderFactory = bob.getStreamReaderFactory(); StreamReaderFactory streamReaderFactory = bob.getStreamReaderFactory();
PacketReaderFactory packetReaderFactory = bob.getPacketReaderFactory(); SyncSessionFactory syncSessionFactory = bob.getSyncSessionFactory();
EventBus eventBus = bob.getEventBus();
// Bob needs a MessagingManager even though we're not using it directly // Bob needs a MessagingManager even though we're not using it directly
bob.getMessagingManager(); bob.getMessagingManager();
@@ -176,10 +159,8 @@ public class SimplexMessagingIntegrationTest extends BriarTestCase {
InputStream streamReader = streamReaderFactory.createStreamReader( InputStream streamReader = streamReaderFactory.createStreamReader(
in, ctx); in, ctx);
// Create an incoming sync session // Create an incoming sync session
PacketReader packetReader = packetReaderFactory.createPacketReader( SyncSession session = syncSessionFactory.createIncomingSession(
streamReader); contactId, streamReader);
SyncSession session = new IncomingSession(db, new ImmediateExecutor(),
eventBus, contactId, packetReader);
// No messages should have been added yet // No messages should have been added yet
assertFalse(listener.messageAdded); assertFalse(listener.messageAdded);
// Read whatever needs to be read // Read whatever needs to be read

View File

@@ -1,17 +1,12 @@
package org.briarproject.sync; package org.briarproject;
import org.briarproject.TestDatabaseModule;
import org.briarproject.TestPluginsModule;
import org.briarproject.TestSystemModule;
import org.briarproject.api.contact.ContactManager; import org.briarproject.api.contact.ContactManager;
import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.event.EventBus; import org.briarproject.api.event.EventBus;
import org.briarproject.api.identity.IdentityManager; import org.briarproject.api.identity.IdentityManager;
import org.briarproject.api.lifecycle.LifecycleManager; import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.messaging.MessagingManager; import org.briarproject.api.messaging.MessagingManager;
import org.briarproject.api.messaging.PrivateMessageFactory; import org.briarproject.api.messaging.PrivateMessageFactory;
import org.briarproject.api.sync.PacketReaderFactory; import org.briarproject.api.sync.SyncSessionFactory;
import org.briarproject.api.sync.PacketWriterFactory;
import org.briarproject.api.transport.KeyManager; import org.briarproject.api.transport.KeyManager;
import org.briarproject.api.transport.StreamReaderFactory; import org.briarproject.api.transport.StreamReaderFactory;
import org.briarproject.api.transport.StreamWriterFactory; import org.briarproject.api.transport.StreamWriterFactory;
@@ -25,6 +20,7 @@ import org.briarproject.identity.IdentityModule;
import org.briarproject.lifecycle.LifecycleModule; import org.briarproject.lifecycle.LifecycleModule;
import org.briarproject.messaging.MessagingModule; import org.briarproject.messaging.MessagingModule;
import org.briarproject.plugins.PluginsModule; import org.briarproject.plugins.PluginsModule;
import org.briarproject.sync.SyncModule;
import org.briarproject.transport.TransportModule; import org.briarproject.transport.TransportModule;
import javax.inject.Singleton; import javax.inject.Singleton;
@@ -32,20 +28,29 @@ import javax.inject.Singleton;
import dagger.Component; import dagger.Component;
@Singleton @Singleton
@Component(modules = {TestDatabaseModule.class, TestPluginsModule.class, @Component(modules = {
TestSystemModule.class, LifecycleModule.class, ContactModule.class, TestDatabaseModule.class,
CryptoModule.class, DatabaseModule.class, EventModule.class, TestPluginsModule.class,
SyncModule.class, DataModule.class, TransportModule.class, TestSystemModule.class,
IdentityModule.class, MessagingModule.class, ClientsModule.class, ClientsModule.class,
PluginsModule.class}) ContactModule.class,
public interface SimplexMessagingComponent { CryptoModule.class,
DataModule.class,
DatabaseModule.class,
EventModule.class,
IdentityModule.class,
LifecycleModule.class,
MessagingModule.class,
PluginsModule.class,
SyncModule.class,
TransportModule.class
})
public interface SimplexMessagingIntegrationTestComponent {
void inject(SimplexMessagingIntegrationTest testCase); void inject(SimplexMessagingIntegrationTest testCase);
LifecycleManager getLifecycleManager(); LifecycleManager getLifecycleManager();
DatabaseComponent getDatabaseComponent();
IdentityManager getIdentityManager(); IdentityManager getIdentityManager();
ContactManager getContactManager(); ContactManager getContactManager();
@@ -56,13 +61,11 @@ public interface SimplexMessagingComponent {
PrivateMessageFactory getPrivateMessageFactory(); PrivateMessageFactory getPrivateMessageFactory();
PacketWriterFactory getPacketWriterFactory();
EventBus getEventBus(); EventBus getEventBus();
StreamWriterFactory getStreamWriterFactory(); StreamWriterFactory getStreamWriterFactory();
StreamReaderFactory getStreamReaderFactory(); StreamReaderFactory getStreamReaderFactory();
PacketReaderFactory getPacketReaderFactory(); SyncSessionFactory getSyncSessionFactory();
} }

View File

@@ -1,9 +1,8 @@
package org.briarproject.protocol; package org.briarproject;
import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.api.TransportId; import org.briarproject.api.TransportId;
import org.briarproject.api.contact.ContactId; import org.briarproject.api.contact.ContactId;
import org.briarproject.api.crypto.CryptoComponent;
import org.briarproject.api.crypto.SecretKey; import org.briarproject.api.crypto.SecretKey;
import org.briarproject.api.sync.Ack; import org.briarproject.api.sync.Ack;
import org.briarproject.api.sync.ClientId; import org.briarproject.api.sync.ClientId;
@@ -23,13 +22,6 @@ import org.briarproject.api.transport.StreamReaderFactory;
import org.briarproject.api.transport.StreamWriterFactory; import org.briarproject.api.transport.StreamWriterFactory;
import org.junit.Test; import org.junit.Test;
import static org.briarproject.api.sync.SyncConstants.MAX_GROUP_DESCRIPTOR_LENGTH;
import static org.briarproject.api.transport.TransportConstants.TAG_LENGTH;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.InputStream; import java.io.InputStream;
@@ -39,8 +31,19 @@ import java.util.Collection;
import javax.inject.Inject; import javax.inject.Inject;
public class ProtocolIntegrationTest extends BriarTestCase { import static org.briarproject.api.sync.SyncConstants.MAX_GROUP_DESCRIPTOR_LENGTH;
import static org.briarproject.api.transport.TransportConstants.TAG_LENGTH;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SyncIntegrationTest extends BriarTestCase {
@Inject
GroupFactory groupFactory;
@Inject
MessageFactory messageFactory;
@Inject @Inject
StreamReaderFactory streamReaderFactory; StreamReaderFactory streamReaderFactory;
@Inject @Inject
@@ -49,37 +52,37 @@ public class ProtocolIntegrationTest extends BriarTestCase {
PacketReaderFactory packetReaderFactory; PacketReaderFactory packetReaderFactory;
@Inject @Inject
PacketWriterFactory packetWriterFactory; PacketWriterFactory packetWriterFactory;
@Inject
CryptoComponent crypto;
private final ContactId contactId; private final ContactId contactId;
private final TransportId transportId; private final TransportId transportId;
private final SecretKey tagKey, headerKey; private final SecretKey tagKey, headerKey;
private final long streamNumber;
private final Message message, message1; private final Message message, message1;
private final Collection<MessageId> messageIds; private final Collection<MessageId> messageIds;
private final ProtocolTestComponent component;
public ProtocolIntegrationTest() throws Exception { public SyncIntegrationTest() throws Exception {
component = DaggerProtocolTestComponent.builder().build(); SyncIntegrationTestComponent component =
DaggerSyncIntegrationTestComponent.builder().build();
component.inject(this); component.inject(this);
contactId = new ContactId(234); contactId = new ContactId(234);
transportId = new TransportId("id"); transportId = new TransportId("id");
// Create the transport keys // Create the transport keys
tagKey = TestUtils.createSecretKey(); tagKey = TestUtils.getSecretKey();
headerKey = TestUtils.createSecretKey(); headerKey = TestUtils.getSecretKey();
streamNumber = 123;
// Create a group // Create a group
GroupFactory groupFactory = component.getGroupFactory();
ClientId clientId = new ClientId(TestUtils.getRandomId()); ClientId clientId = new ClientId(TestUtils.getRandomId());
byte[] descriptor = new byte[MAX_GROUP_DESCRIPTOR_LENGTH]; byte[] descriptor = new byte[MAX_GROUP_DESCRIPTOR_LENGTH];
Group group = groupFactory.createGroup(clientId, descriptor); Group group = groupFactory.createGroup(clientId, descriptor);
// Add two messages to the group // Add two messages to the group
MessageFactory messageFactory = component.getMessageFactory();
long timestamp = System.currentTimeMillis(); long timestamp = System.currentTimeMillis();
String messageBody = "Hello world"; byte[] body = "Hello world".getBytes("UTF-8");
message = messageFactory.createMessage(group.getId(), timestamp, message = messageFactory.createMessage(group.getId(), timestamp, body);
messageBody.getBytes("UTF-8")); message1 = messageFactory.createMessage(group.getId(), timestamp, body);
message1 = messageFactory.createMessage(group.getId(), timestamp,
messageBody.getBytes("UTF-8"));
messageIds = Arrays.asList(message.getId(), message1.getId()); messageIds = Arrays.asList(message.getId(), message1.getId());
} }
@@ -91,19 +94,16 @@ public class ProtocolIntegrationTest extends BriarTestCase {
private byte[] write() throws Exception { private byte[] write() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
StreamContext ctx = new StreamContext(contactId, transportId, tagKey, StreamContext ctx = new StreamContext(contactId, transportId, tagKey,
headerKey, 0); headerKey, streamNumber);
OutputStream streamWriter = OutputStream streamWriter = streamWriterFactory.createStreamWriter(out,
streamWriterFactory.createStreamWriter(out, ctx); ctx);
PacketWriter packetWriter = packetWriterFactory.createPacketWriter( PacketWriter packetWriter = packetWriterFactory.createPacketWriter(
streamWriter); streamWriter);
packetWriter.writeAck(new Ack(messageIds)); packetWriter.writeAck(new Ack(messageIds));
packetWriter.writeMessage(message.getRaw()); packetWriter.writeMessage(message.getRaw());
packetWriter.writeMessage(message1.getRaw()); packetWriter.writeMessage(message1.getRaw());
packetWriter.writeOffer(new Offer(messageIds)); packetWriter.writeOffer(new Offer(messageIds));
packetWriter.writeRequest(new Request(messageIds)); packetWriter.writeRequest(new Request(messageIds));
streamWriter.flush(); streamWriter.flush();
@@ -111,14 +111,21 @@ public class ProtocolIntegrationTest extends BriarTestCase {
} }
private void read(byte[] connectionData) throws Exception { private void read(byte[] connectionData) throws Exception {
// Calculate the expected tag
byte[] expectedTag = new byte[TAG_LENGTH];
crypto.encodeTag(expectedTag, tagKey, streamNumber);
// Read the tag
InputStream in = new ByteArrayInputStream(connectionData); InputStream in = new ByteArrayInputStream(connectionData);
byte[] tag = new byte[TAG_LENGTH]; byte[] tag = new byte[TAG_LENGTH];
assertEquals(TAG_LENGTH, in.read(tag, 0, TAG_LENGTH)); assertEquals(TAG_LENGTH, in.read(tag, 0, TAG_LENGTH));
// FIXME: Check that the expected tag was received assertArrayEquals(expectedTag, tag);
// Create the readers
StreamContext ctx = new StreamContext(contactId, transportId, tagKey, StreamContext ctx = new StreamContext(contactId, transportId, tagKey,
headerKey, 0); headerKey, 0);
InputStream streamReader = InputStream streamReader = streamReaderFactory.createStreamReader(in,
streamReaderFactory.createStreamReader(in, ctx); ctx);
PacketReader packetReader = packetReaderFactory.createPacketReader( PacketReader packetReader = packetReaderFactory.createPacketReader(
streamReader); streamReader);
@@ -127,7 +134,7 @@ public class ProtocolIntegrationTest extends BriarTestCase {
Ack a = packetReader.readAck(); Ack a = packetReader.readAck();
assertEquals(messageIds, a.getMessageIds()); assertEquals(messageIds, a.getMessageIds());
// Read and verify the messages // Read the messages
assertTrue(packetReader.hasMessage()); assertTrue(packetReader.hasMessage());
Message m = packetReader.readMessage(); Message m = packetReader.readMessage();
checkMessageEquality(message, m); checkMessageEquality(message, m);
@@ -150,9 +157,11 @@ public class ProtocolIntegrationTest extends BriarTestCase {
} }
private void checkMessageEquality(Message m1, Message m2) { private void checkMessageEquality(Message m1, Message m2) {
assertEquals(m1.getId(), m2.getId()); assertArrayEquals(m1.getId().getBytes(), m2.getId().getBytes());
assertArrayEquals(m1.getGroupId().getBytes(),
m2.getGroupId().getBytes());
assertEquals(m1.getTimestamp(), m2.getTimestamp()); assertEquals(m1.getTimestamp(), m2.getTimestamp());
assertEquals(m1.getLength(), m2.getLength());
assertArrayEquals(m1.getRaw(), m2.getRaw()); assertArrayEquals(m1.getRaw(), m2.getRaw());
} }
} }

View File

@@ -0,0 +1,20 @@
package org.briarproject;
import org.briarproject.crypto.CryptoModule;
import org.briarproject.sync.SyncModule;
import org.briarproject.transport.TransportModule;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {
TestSystemModule.class,
CryptoModule.class,
SyncModule.class,
TransportModule.class
})
public interface SyncIntegrationTestComponent {
void inject(SyncIntegrationTest testCase);
}

View File

@@ -1,26 +0,0 @@
package org.briarproject.protocol;
import org.briarproject.TestDatabaseModule;
import org.briarproject.TestSystemModule;
import org.briarproject.api.sync.GroupFactory;
import org.briarproject.api.sync.MessageFactory;
import org.briarproject.crypto.CryptoModule;
import org.briarproject.data.DataModule;
import org.briarproject.db.DatabaseModule;
import org.briarproject.event.EventModule;
import org.briarproject.sync.SyncModule;
import org.briarproject.transport.TransportModule;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {TestDatabaseModule.class, TestSystemModule.class,
CryptoModule.class, DatabaseModule.class, EventModule.class,
SyncModule.class, DataModule.class, TransportModule.class})
public interface ProtocolTestComponent {
void inject(ProtocolIntegrationTest testCase);
GroupFactory getGroupFactory();
MessageFactory getMessageFactory();
}

View File

@@ -1,29 +0,0 @@
package org.briarproject.sync;
import org.briarproject.TestDatabaseModule;
import org.briarproject.TestLifecycleModule;
import org.briarproject.TestSystemModule;
import org.briarproject.clients.ClientsModule;
import org.briarproject.contact.ContactModule;
import org.briarproject.crypto.CryptoModule;
import org.briarproject.data.DataModule;
import org.briarproject.db.DatabaseModule;
import org.briarproject.event.EventModule;
import org.briarproject.forum.ForumModule;
import org.briarproject.identity.IdentityModule;
import org.briarproject.messaging.MessagingModule;
import org.briarproject.transport.TransportModule;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {TestDatabaseModule.class, TestLifecycleModule.class,
TestSystemModule.class, ContactModule.class, CryptoModule.class,
DatabaseModule.class, EventModule.class, SyncModule.class,
DataModule.class, TransportModule.class, ForumModule.class,
IdentityModule.class, MessagingModule.class, ClientsModule.class})
public interface ConstantsComponent {
void inject(ConstantsTest testCase);
}

View File

@@ -26,9 +26,12 @@ import javax.inject.Singleton;
import dagger.Component; import dagger.Component;
@Singleton @Singleton
@Component( @Component(modules = {
modules = {CoreModule.class, AppModule.class, AndroidModule.class, CoreModule.class,
AndroidPluginsModule.class, AndroidSystemModule.class}) AppModule.class,
AndroidPluginsModule.class,
AndroidSystemModule.class
})
public interface AndroidComponent extends CoreEagerSingletons { public interface AndroidComponent extends CoreEagerSingletons {
void inject(SplashScreenActivity activity); void inject(SplashScreenActivity activity);
@@ -78,6 +81,5 @@ public interface AndroidComponent extends CoreEagerSingletons {
void inject(ShowQrCodeFragment fragment); void inject(ShowQrCodeFragment fragment);
// Eager singleton load // Eager singleton load
void inject(AndroidModule.EagerSingletons init); void inject(AppModule.EagerSingletons init);
} }

View File

@@ -3,6 +3,6 @@ package org.briarproject.android;
public class AndroidEagerSingletons { public class AndroidEagerSingletons {
public static void initEagerSingletons(AndroidComponent c) { public static void initEagerSingletons(AndroidComponent c) {
c.inject(new AndroidModule.EagerSingletons()); c.inject(new AppModule.EagerSingletons());
} }
} }

View File

@@ -1,100 +0,0 @@
package org.briarproject.android;
import android.app.Application;
import android.content.Context;
import org.briarproject.android.api.AndroidNotificationManager;
import org.briarproject.android.api.ReferenceManager;
import org.briarproject.api.crypto.SecretKey;
import org.briarproject.api.db.DatabaseConfig;
import org.briarproject.api.event.EventBus;
import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.ui.UiCallback;
import java.io.File;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
@Module
public class AndroidModule {
static class EagerSingletons {
@Inject
AndroidNotificationManager androidNotificationManager;
}
private final UiCallback uiCallback;
public AndroidModule() {
// Use a dummy UI callback
uiCallback = new UiCallback() {
public int showChoice(String[] options, String... message) {
throw new UnsupportedOperationException();
}
public boolean showConfirmationMessage(String... message) {
throw new UnsupportedOperationException();
}
public void showMessage(String... message) {
throw new UnsupportedOperationException();
}
};
}
@Provides
public UiCallback provideUICallback() {
return uiCallback;
}
@Provides
@Singleton
public DatabaseConfig provideDatabaseConfig(Application app) {
final File dir = app.getApplicationContext().getDir("db", Context.MODE_PRIVATE);
return new DatabaseConfig() {
private volatile SecretKey key = null;
public boolean databaseExists() {
return dir.isDirectory() && dir.listFiles().length > 0;
}
public File getDatabaseDirectory() {
return dir;
}
public void setEncryptionKey(SecretKey key) {
this.key = key;
}
public SecretKey getEncryptionKey() {
return key;
}
public long getMaxSize() {
return Long.MAX_VALUE;
}
};
}
@Provides
@Singleton
ReferenceManager provideReferenceManager() {
return new ReferenceManagerImpl();
}
@Provides
@Singleton
AndroidNotificationManager provideAndroidNotificationManager(
LifecycleManager lifecycleManager, EventBus eventBus,
AndroidNotificationManagerImpl notificationManager) {
lifecycleManager.registerService(notificationManager);
eventBus.addListener(notificationManager);
return notificationManager;
}
}

View File

@@ -2,18 +2,51 @@ package org.briarproject.android;
import android.app.Application; import android.app.Application;
import org.briarproject.android.api.AndroidNotificationManager;
import org.briarproject.android.api.ReferenceManager;
import org.briarproject.api.crypto.SecretKey;
import org.briarproject.api.db.DatabaseConfig;
import org.briarproject.api.event.EventBus;
import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.ui.UiCallback;
import java.io.File;
import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import dagger.Module; import dagger.Module;
import dagger.Provides; import dagger.Provides;
import static android.content.Context.MODE_PRIVATE;
@Module @Module
public class AppModule { public class AppModule {
Application application; static class EagerSingletons {
@Inject
AndroidNotificationManager androidNotificationManager;
}
private final Application application;
private final UiCallback uiCallback;
public AppModule(Application application) { public AppModule(Application application) {
this.application = application; this.application = application;
uiCallback = new UiCallback() {
public int showChoice(String[] options, String... message) {
throw new UnsupportedOperationException();
}
public boolean showConfirmationMessage(String... message) {
throw new UnsupportedOperationException();
}
public void showMessage(String... message) {
throw new UnsupportedOperationException();
}
};
} }
@Provides @Provides
@@ -21,4 +54,55 @@ public class AppModule {
Application providesApplication() { Application providesApplication() {
return application; return application;
} }
@Provides
public UiCallback provideUICallback() {
return uiCallback;
}
@Provides
@Singleton
public DatabaseConfig provideDatabaseConfig(Application app) {
final File dir = app.getApplicationContext().getDir("db", MODE_PRIVATE);
return new DatabaseConfig() {
private volatile SecretKey key = null;
public boolean databaseExists() {
return dir.isDirectory() && dir.listFiles().length > 0;
}
public File getDatabaseDirectory() {
return dir;
}
public void setEncryptionKey(SecretKey key) {
this.key = key;
}
public SecretKey getEncryptionKey() {
return key;
}
public long getMaxSize() {
return Long.MAX_VALUE;
}
};
}
@Provides
@Singleton
ReferenceManager provideReferenceManager() {
return new ReferenceManagerImpl();
}
@Provides
@Singleton
AndroidNotificationManager provideAndroidNotificationManager(
LifecycleManager lifecycleManager, EventBus eventBus,
AndroidNotificationManagerImpl notificationManager) {
lifecycleManager.registerService(notificationManager);
eventBus.addListener(notificationManager);
return notificationManager;
}
} }

View File

@@ -1,17 +1,12 @@
package org.briarproject.android; package org.briarproject.android;
import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle; import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import android.view.View; import android.view.View;
import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodManager;
import javax.inject.Inject;
import static android.view.WindowManager.LayoutParams.FLAG_SECURE; import static android.view.WindowManager.LayoutParams.FLAG_SECURE;
import static android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT; import static android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT;
import static org.briarproject.android.TestingConstants.PREVENT_SCREENSHOTS; import static org.briarproject.android.TestingConstants.PREVENT_SCREENSHOTS;
@@ -28,9 +23,8 @@ public abstract class BaseActivity extends AppCompatActivity {
if (PREVENT_SCREENSHOTS) getWindow().addFlags(FLAG_SECURE); if (PREVENT_SCREENSHOTS) getWindow().addFlags(FLAG_SECURE);
AndroidComponent component = BriarApplication application = (BriarApplication) getApplication();
((BriarApplication) getApplication()).getApplicationComponent(); injectActivity(application.getApplicationComponent());
injectActivity(component);
} }
public abstract void injectActivity(AndroidComponent component); public abstract void injectActivity(AndroidComponent component);

View File

@@ -1,13 +1,13 @@
package org.briarproject.android; package org.briarproject.android;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.logging.Logger;
import android.app.Application; import android.app.Application;
import android.content.Context; import android.content.Context;
import org.briarproject.CoreModule; import org.briarproject.CoreModule;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.logging.Logger;
public class BriarApplication extends Application { public class BriarApplication extends Application {
private static final Logger LOG = private static final Logger LOG =
@@ -18,7 +18,7 @@ public class BriarApplication extends Application {
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
LOG.info("Application Created"); LOG.info("Created");
UncaughtExceptionHandler oldHandler = UncaughtExceptionHandler oldHandler =
Thread.getDefaultUncaughtExceptionHandler(); Thread.getDefaultUncaughtExceptionHandler();
Context ctx = getApplicationContext(); Context ctx = getApplicationContext();
@@ -27,7 +27,6 @@ public class BriarApplication extends Application {
applicationComponent = DaggerAndroidComponent.builder() applicationComponent = DaggerAndroidComponent.builder()
.appModule(new AppModule(this)) .appModule(new AppModule(this))
.androidModule(new AndroidModule())
.build(); .build();
// We need to load the eager singletons directly after making the // We need to load the eager singletons directly after making the

View File

@@ -55,8 +55,8 @@ public class BriarService extends Service {
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
((BriarApplication) this.getApplication()) BriarApplication application = (BriarApplication) getApplication();
.getApplicationComponent().inject(this); application.getApplicationComponent().inject(this);
LOG.info("Created"); LOG.info("Created");
if (created.getAndSet(true)) { if (created.getAndSet(true)) {

View File

@@ -5,7 +5,6 @@ import android.os.Bundle;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import org.briarproject.android.AndroidComponent; import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BriarActivity;
import org.briarproject.android.BriarApplication; import org.briarproject.android.BriarApplication;
public abstract class BaseFragment extends Fragment { public abstract class BaseFragment extends Fragment {
@@ -14,8 +13,6 @@ public abstract class BaseFragment extends Fragment {
protected BaseFragmentListener listener; protected BaseFragmentListener listener;
protected BriarActivity briarActivity;
@Override @Override
public void onAttach(Context context) { public void onAttach(Context context) {
super.onAttach(context); super.onAttach(context);
@@ -31,15 +28,15 @@ public abstract class BaseFragment extends Fragment {
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
AndroidComponent component = BriarApplication application =
((BriarApplication) getActivity().getApplication()) (BriarApplication) getActivity().getApplication();
.getApplicationComponent(); injectActivity(application.getApplicationComponent());
injectActivity(component);
} }
public abstract void injectActivity(AndroidComponent component); public abstract void injectActivity(AndroidComponent component);
public interface BaseFragmentListener { public interface BaseFragmentListener {
void showLoadingScreen(boolean isBlocking, int stringId); void showLoadingScreen(boolean isBlocking, int stringId);
void hideLoadingScreen(); void hideLoadingScreen();
@@ -48,5 +45,4 @@ public abstract class BaseFragment extends Fragment {
void runOnDbThread(Runnable runnable); void runOnDbThread(Runnable runnable);
} }
} }

View File

@@ -2,7 +2,7 @@ package org.briarproject;
import org.briarproject.contact.ContactModule; import org.briarproject.contact.ContactModule;
import org.briarproject.crypto.CryptoModule; import org.briarproject.crypto.CryptoModule;
import org.briarproject.db.DatabaseModule; import org.briarproject.db.DatabaseExecutorModule;
import org.briarproject.forum.ForumModule; import org.briarproject.forum.ForumModule;
import org.briarproject.introduction.IntroductionModule; import org.briarproject.introduction.IntroductionModule;
import org.briarproject.lifecycle.LifecycleModule; import org.briarproject.lifecycle.LifecycleModule;
@@ -13,16 +13,26 @@ import org.briarproject.sync.SyncModule;
import org.briarproject.transport.TransportModule; import org.briarproject.transport.TransportModule;
public interface CoreEagerSingletons { public interface CoreEagerSingletons {
void inject(ContactModule.EagerSingletons init);
void inject(CryptoModule.EagerSingletons init);
void inject(DatabaseModule.EagerSingletons init);
void inject(ForumModule.EagerSingletons init);
void inject(IntroductionModule.EagerSingletons init);
void inject(LifecycleModule.EagerSingletons init);
void inject(MessagingModule.EagerSingletons init);
void inject(PluginsModule.EagerSingletons init);
void inject(PropertiesModule.EagerSingletons init);
void inject(SyncModule.EagerSingletons init);
void inject(TransportModule.EagerSingletons init);
void inject(ContactModule.EagerSingletons init);
void inject(CryptoModule.EagerSingletons init);
void inject(DatabaseExecutorModule.EagerSingletons init);
void inject(ForumModule.EagerSingletons init);
void inject(IntroductionModule.EagerSingletons init);
void inject(LifecycleModule.EagerSingletons init);
void inject(MessagingModule.EagerSingletons init);
void inject(PluginsModule.EagerSingletons init);
void inject(PropertiesModule.EagerSingletons init);
void inject(SyncModule.EagerSingletons init);
void inject(TransportModule.EagerSingletons init);
} }

View File

@@ -4,6 +4,7 @@ import org.briarproject.clients.ClientsModule;
import org.briarproject.contact.ContactModule; import org.briarproject.contact.ContactModule;
import org.briarproject.crypto.CryptoModule; import org.briarproject.crypto.CryptoModule;
import org.briarproject.data.DataModule; import org.briarproject.data.DataModule;
import org.briarproject.db.DatabaseExecutorModule;
import org.briarproject.db.DatabaseModule; import org.briarproject.db.DatabaseModule;
import org.briarproject.event.EventModule; import org.briarproject.event.EventModule;
import org.briarproject.forum.ForumModule; import org.briarproject.forum.ForumModule;
@@ -23,20 +24,35 @@ import org.briarproject.transport.TransportModule;
import dagger.Module; import dagger.Module;
@Module(includes = {DatabaseModule.class, @Module(includes = {
CryptoModule.class, LifecycleModule.class, ReliabilityModule.class, ClientsModule.class,
MessagingModule.class, InvitationModule.class, KeyAgreementModule.class, ContactModule.class,
CryptoModule.class,
DataModule.class,
DatabaseModule.class,
DatabaseExecutorModule.class,
EventModule.class,
ForumModule.class, ForumModule.class,
IdentityModule.class, EventModule.class, DataModule.class, IdentityModule.class,
ContactModule.class, PropertiesModule.class, TransportModule.class, IntroductionModule.class,
SyncModule.class, SettingsModule.class, ClientsModule.class, InvitationModule.class,
SystemModule.class, PluginsModule.class, IntroductionModule.class}) KeyAgreementModule.class,
LifecycleModule.class,
MessagingModule.class,
PluginsModule.class,
PropertiesModule.class,
ReliabilityModule.class,
SettingsModule.class,
SyncModule.class,
SystemModule.class,
TransportModule.class
})
public class CoreModule { public class CoreModule {
public static void initEagerSingletons(CoreEagerSingletons c) { public static void initEagerSingletons(CoreEagerSingletons c) {
c.inject(new ContactModule.EagerSingletons()); c.inject(new ContactModule.EagerSingletons());
c.inject(new CryptoModule.EagerSingletons()); c.inject(new CryptoModule.EagerSingletons());
c.inject(new DatabaseModule.EagerSingletons()); c.inject(new DatabaseExecutorModule.EagerSingletons());
c.inject(new ForumModule.EagerSingletons()); c.inject(new ForumModule.EagerSingletons());
c.inject(new LifecycleModule.EagerSingletons()); c.inject(new LifecycleModule.EagerSingletons());
c.inject(new MessagingModule.EagerSingletons()); c.inject(new MessagingModule.EagerSingletons());

View File

@@ -0,0 +1,59 @@
package org.briarproject.db;
import org.briarproject.api.db.DatabaseExecutor;
import org.briarproject.api.lifecycle.LifecycleManager;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import static java.util.concurrent.TimeUnit.SECONDS;
@Module
public class DatabaseExecutorModule {
public static class EagerSingletons {
@Inject
@DatabaseExecutor
ExecutorService executorService;
}
private final ExecutorService databaseExecutor;
public DatabaseExecutorModule() {
// Use an unbounded queue
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
// Discard tasks that are submitted during shutdown
RejectedExecutionHandler policy =
new ThreadPoolExecutor.DiscardPolicy();
// Use a single thread and keep it in the pool for 60 secs
databaseExecutor = new ThreadPoolExecutor(0, 1, 60, SECONDS, queue,
policy);
}
@Provides
@Singleton
@DatabaseExecutor
ExecutorService provideDatabaseExecutorService(
LifecycleManager lifecycleManager) {
lifecycleManager.registerForShutdown(databaseExecutor);
return databaseExecutor;
}
@Provides
@Singleton
@DatabaseExecutor
Executor provideDatabaseExecutor(
@DatabaseExecutor ExecutorService dbExecutor) {
return dbExecutor;
}
}

View File

@@ -2,50 +2,21 @@ package org.briarproject.db;
import org.briarproject.api.db.DatabaseComponent; import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.db.DatabaseConfig; import org.briarproject.api.db.DatabaseConfig;
import org.briarproject.api.db.DatabaseExecutor;
import org.briarproject.api.event.EventBus; import org.briarproject.api.event.EventBus;
import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.lifecycle.ShutdownManager; import org.briarproject.api.lifecycle.ShutdownManager;
import org.briarproject.api.system.Clock; import org.briarproject.api.system.Clock;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.sql.Connection; import java.sql.Connection;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import dagger.Module; import dagger.Module;
import dagger.Provides; import dagger.Provides;
import static java.util.concurrent.TimeUnit.SECONDS;
@Module @Module
public class DatabaseModule { public class DatabaseModule {
public static class EagerSingletons {
@Inject
@DatabaseExecutor ExecutorService executorService;
}
private final ExecutorService databaseExecutor;
public DatabaseModule() {
// Use an unbounded queue
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
// Discard tasks that are submitted during shutdown
RejectedExecutionHandler policy =
new ThreadPoolExecutor.DiscardPolicy();
// Use a single thread and keep it in the pool for 60 secs
databaseExecutor = new ThreadPoolExecutor(0, 1, 60, SECONDS, queue,
policy);
}
@Provides @Provides
@Singleton @Singleton
Database<Connection> provideDatabase(DatabaseConfig config, Database<Connection> provideDatabase(DatabaseConfig config,
@@ -53,21 +24,11 @@ public class DatabaseModule {
return new H2Database(config, random, clock); return new H2Database(config, random, clock);
} }
@Provides @Singleton @Provides
@Singleton
DatabaseComponent provideDatabaseComponent(Database<Connection> db, DatabaseComponent provideDatabaseComponent(Database<Connection> db,
EventBus eventBus, ShutdownManager shutdown) { EventBus eventBus, ShutdownManager shutdown) {
return new DatabaseComponentImpl<Connection>(db, Connection.class, return new DatabaseComponentImpl<Connection>(db, Connection.class,
eventBus, shutdown); eventBus, shutdown);
} }
@Provides @Singleton @DatabaseExecutor
ExecutorService provideDatabaseExecutorService(LifecycleManager lifecycleManager) {
lifecycleManager.registerForShutdown(databaseExecutor);
return databaseExecutor;
}
@Provides @Singleton @DatabaseExecutor
Executor provideDatabaseExecutor(@DatabaseExecutor ExecutorService dbExecutor) {
return dbExecutor;
}
} }

View File

@@ -27,7 +27,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executor;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.inject.Inject; import javax.inject.Inject;
@@ -41,7 +41,7 @@ class KeyManagerImpl implements KeyManager, Service, EventListener {
private final DatabaseComponent db; private final DatabaseComponent db;
private final CryptoComponent crypto; private final CryptoComponent crypto;
private final ExecutorService dbExecutor; private final Executor dbExecutor;
private final PluginConfig pluginConfig; private final PluginConfig pluginConfig;
private final Timer timer; private final Timer timer;
private final Clock clock; private final Clock clock;
@@ -50,8 +50,8 @@ class KeyManagerImpl implements KeyManager, Service, EventListener {
@Inject @Inject
KeyManagerImpl(DatabaseComponent db, CryptoComponent crypto, KeyManagerImpl(DatabaseComponent db, CryptoComponent crypto,
@DatabaseExecutor ExecutorService dbExecutor, @DatabaseExecutor Executor dbExecutor, PluginConfig pluginConfig,
PluginConfig pluginConfig, Timer timer, Clock clock) { Timer timer, Clock clock) {
this.db = db; this.db = db;
this.crypto = crypto; this.crypto = crypto;
this.dbExecutor = dbExecutor; this.dbExecutor = dbExecutor;

View File

@@ -1,27 +1,28 @@
package org.briarproject; package org.briarproject;
import org.briarproject.api.db.DatabaseConfig; import org.briarproject.api.db.DatabaseConfig;
import org.briarproject.api.db.DatabaseExecutor;
import org.briarproject.db.DatabaseModule;
import java.io.File; import java.io.File;
import java.util.concurrent.Executor;
import javax.inject.Singleton;
import dagger.Module; import dagger.Module;
import dagger.Provides; import dagger.Provides;
@Module @Module
public class TestDatabaseModule { public class TestDatabaseModule extends DatabaseModule {
private final DatabaseConfig config; private final DatabaseConfig config;
public TestDatabaseModule() { public TestDatabaseModule() {
this(new File("."), Long.MAX_VALUE); this(new File("."));
} }
public TestDatabaseModule(File dir) { public TestDatabaseModule(File dir) {
this(dir, Long.MAX_VALUE); config = new TestDatabaseConfig(dir, Long.MAX_VALUE);
}
public TestDatabaseModule(File dir, long maxSize) {
this.config = new TestDatabaseConfig(dir, maxSize);
} }
@Provides @Provides
@@ -29,4 +30,10 @@ public class TestDatabaseModule {
return config; return config;
} }
@Provides
@Singleton
@DatabaseExecutor
Executor provideDatabaseExecutor() {
return new ImmediateExecutor();
}
} }

View File

@@ -2,15 +2,9 @@ package org.briarproject;
import org.briarproject.api.system.SeedProvider; import org.briarproject.api.system.SeedProvider;
import java.util.Random;
public class TestSeedProvider implements SeedProvider { public class TestSeedProvider implements SeedProvider {
private final Random random = new Random();
public byte[] getSeed() { public byte[] getSeed() {
byte[] seed = new byte[32]; return TestUtils.getRandomBytes(32);
random.nextBytes(seed);
return seed;
} }
} }

View File

@@ -1,15 +1,13 @@
package org.briarproject; package org.briarproject;
import org.briarproject.api.UniqueId; import org.briarproject.api.UniqueId;
import org.briarproject.api.crypto.SecretKey;
import org.briarproject.util.FileUtils; import org.briarproject.util.FileUtils;
import java.io.File; import java.io.File;
import java.util.Random; import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.briarproject.api.UniqueId;
import org.briarproject.api.crypto.SecretKey;
public class TestUtils { public class TestUtils {
private static final AtomicInteger nextTestDir = private static final AtomicInteger nextTestDir =
@@ -26,28 +24,24 @@ public class TestUtils {
testDir.getParentFile().delete(); // Delete if empty testDir.getParentFile().delete(); // Delete if empty
} }
public static byte[] getRandomId() {
byte[] b = new byte[UniqueId.LENGTH];
random.nextBytes(b);
return b;
}
public static byte[] getRandomBytes(int length) { public static byte[] getRandomBytes(int length) {
byte[] b = new byte[length]; byte[] b = new byte[length];
random.nextBytes(b); random.nextBytes(b);
return b; return b;
} }
public static String createRandomString(int length) { public static byte[] getRandomId() {
return getRandomBytes(UniqueId.LENGTH);
}
public static String getRandomString(int length) {
char[] c = new char[length]; char[] c = new char[length];
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
c[i] = (char) ('a' + random.nextInt(26)); c[i] = (char) ('a' + random.nextInt(26));
return new String(c); return new String(c);
} }
public static SecretKey createSecretKey() { public static SecretKey getSecretKey() {
byte[] b = new byte[SecretKey.LENGTH]; return new SecretKey(getRandomBytes(SecretKey.LENGTH));
random.nextBytes(b);
return new SecretKey(b);
} }
} }

View File

@@ -13,7 +13,7 @@ import static org.junit.Assert.assertArrayEquals;
public class KeyAgreementTest extends BriarTestCase { public class KeyAgreementTest extends BriarTestCase {
@Test @Test
public void testBTKeyAgreement() throws Exception { public void testDeriveMasterSecret() throws Exception {
SeedProvider seedProvider = new TestSeedProvider(); SeedProvider seedProvider = new TestSeedProvider();
CryptoComponent crypto = new CryptoComponentImpl(seedProvider); CryptoComponent crypto = new CryptoComponentImpl(seedProvider);
KeyPair aPair = crypto.generateAgreementKeyPair(); KeyPair aPair = crypto.generateAgreementKeyPair();
@@ -26,7 +26,7 @@ public class KeyAgreementTest extends BriarTestCase {
} }
@Test @Test
public void testKeyAgreement() throws Exception { public void testDeriveSharedSecret() throws Exception {
SeedProvider seedProvider = new TestSeedProvider(); SeedProvider seedProvider = new TestSeedProvider();
CryptoComponent crypto = new CryptoComponentImpl(seedProvider); CryptoComponent crypto = new CryptoComponentImpl(seedProvider);
KeyPair aPair = crypto.generateAgreementKeyPair(); KeyPair aPair = crypto.generateAgreementKeyPair();

View File

@@ -24,7 +24,7 @@ public class KeyDerivationTest extends BriarTestCase {
public KeyDerivationTest() { public KeyDerivationTest() {
crypto = new CryptoComponentImpl(new TestSeedProvider()); crypto = new CryptoComponentImpl(new TestSeedProvider());
master = TestUtils.createSecretKey(); master = TestUtils.getSecretKey();
} }
@Test @Test
@@ -120,7 +120,7 @@ public class KeyDerivationTest extends BriarTestCase {
@Test @Test
public void testMasterKeyAffectsOutput() { public void testMasterKeyAffectsOutput() {
SecretKey master1 = TestUtils.createSecretKey(); SecretKey master1 = TestUtils.getSecretKey();
assertFalse(Arrays.equals(master.getBytes(), master1.getBytes())); assertFalse(Arrays.equals(master.getBytes(), master1.getBytes()));
TransportKeys k = crypto.deriveTransportKeys(transportId, master, TransportKeys k = crypto.deriveTransportKeys(transportId, master,
123, true); 123, true);

View File

@@ -2,23 +2,37 @@ package org.briarproject.crypto;
import org.briarproject.BriarTestCase; import org.briarproject.BriarTestCase;
import org.briarproject.TestSeedProvider; import org.briarproject.TestSeedProvider;
import org.briarproject.TestUtils;
import org.briarproject.api.crypto.KeyPair; import org.briarproject.api.crypto.KeyPair;
import org.briarproject.api.crypto.KeyParser; import org.briarproject.api.crypto.KeyParser;
import org.briarproject.api.crypto.PrivateKey; import org.briarproject.api.crypto.PrivateKey;
import org.briarproject.api.crypto.PublicKey; import org.briarproject.api.crypto.PublicKey;
import org.briarproject.api.crypto.Signature;
import org.junit.Test; import org.junit.Test;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.util.Random;
import static org.briarproject.api.identity.AuthorConstants.MAX_PUBLIC_KEY_LENGTH;
import static org.briarproject.api.identity.AuthorConstants.MAX_SIGNATURE_LENGTH;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.fail; import static org.junit.Assert.assertTrue;
public class KeyEncodingAndParsingTest extends BriarTestCase { public class KeyEncodingAndParsingTest extends BriarTestCase {
private final CryptoComponentImpl crypto = private final CryptoComponentImpl crypto =
new CryptoComponentImpl(new TestSeedProvider()); new CryptoComponentImpl(new TestSeedProvider());
@Test
public void testAgreementPublicKeyLength() throws Exception {
// Generate 10 agreement key pairs
for (int i = 0; i < 10; i++) {
KeyPair keyPair = crypto.generateSignatureKeyPair();
// Check the length of the public key
byte[] publicKey = keyPair.getPublic().getEncoded();
assertTrue(publicKey.length <= MAX_PUBLIC_KEY_LENGTH);
}
}
@Test @Test
public void testAgreementPublicKeyEncodingAndParsing() throws Exception { public void testAgreementPublicKeyEncodingAndParsing() throws Exception {
KeyParser parser = crypto.getAgreementKeyParser(); KeyParser parser = crypto.getAgreementKeyParser();
@@ -61,27 +75,46 @@ public class KeyEncodingAndParsingTest extends BriarTestCase {
int pubLength = p.getPublic().getEncoded().length; int pubLength = p.getPublic().getEncoded().length;
int privLength = p.getPrivate().getEncoded().length; int privLength = p.getPrivate().getEncoded().length;
// Parse some random byte arrays - expect GeneralSecurityException // Parse some random byte arrays - expect GeneralSecurityException
Random random = new Random();
byte[] pubFuzz = new byte[pubLength];
byte[] privFuzz = new byte[privLength];
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
random.nextBytes(pubFuzz);
try { try {
parser.parsePublicKey(pubFuzz); parser.parsePublicKey(TestUtils.getRandomBytes(pubLength));
} catch (GeneralSecurityException expected) { } catch (GeneralSecurityException expected) {
} catch (Exception e) { // Expected
fail();
} }
random.nextBytes(privFuzz);
try { try {
parser.parsePrivateKey(privFuzz); parser.parsePrivateKey(TestUtils.getRandomBytes(privLength));
} catch (GeneralSecurityException expected) { } catch (GeneralSecurityException expected) {
} catch (Exception e) { // Expected
fail();
} }
} }
} }
@Test
public void testSignaturePublicKeyLength() throws Exception {
// Generate 10 signature key pairs
for (int i = 0; i < 10; i++) {
KeyPair keyPair = crypto.generateSignatureKeyPair();
// Check the length of the public key
byte[] publicKey = keyPair.getPublic().getEncoded();
assertTrue(publicKey.length <= MAX_PUBLIC_KEY_LENGTH);
}
}
@Test
public void testSignatureLength() throws Exception {
Signature sig = crypto.getSignature();
// Generate 10 signature key pairs
for (int i = 0; i < 10; i++) {
KeyPair keyPair = crypto.generateSignatureKeyPair();
// Sign some random data and check the length of the signature
byte[] toBeSigned = TestUtils.getRandomBytes(1234);
sig.initSign(keyPair.getPrivate());
sig.update(toBeSigned);
byte[] signature = sig.sign();
assertTrue(signature.length <= MAX_SIGNATURE_LENGTH);
}
}
@Test @Test
public void testSignaturePublicKeyEncodingAndParsing() throws Exception { public void testSignaturePublicKeyEncodingAndParsing() throws Exception {
KeyParser parser = crypto.getSignatureKeyParser(); KeyParser parser = crypto.getSignatureKeyParser();
@@ -124,23 +157,16 @@ public class KeyEncodingAndParsingTest extends BriarTestCase {
int pubLength = p.getPublic().getEncoded().length; int pubLength = p.getPublic().getEncoded().length;
int privLength = p.getPrivate().getEncoded().length; int privLength = p.getPrivate().getEncoded().length;
// Parse some random byte arrays - expect GeneralSecurityException // Parse some random byte arrays - expect GeneralSecurityException
Random random = new Random();
byte[] pubFuzz = new byte[pubLength];
byte[] privFuzz = new byte[privLength];
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
random.nextBytes(pubFuzz);
try { try {
parser.parsePublicKey(pubFuzz); parser.parsePublicKey(TestUtils.getRandomBytes(pubLength));
} catch (GeneralSecurityException expected) { } catch (GeneralSecurityException expected) {
} catch (Exception e) { // Expected
fail();
} }
random.nextBytes(privFuzz);
try { try {
parser.parsePrivateKey(privFuzz); parser.parsePrivateKey(TestUtils.getRandomBytes(privLength));
} catch (GeneralSecurityException expected) { } catch (GeneralSecurityException expected) {
} catch (Exception e) { // Expected
fail();
} }
} }
} }

View File

@@ -2,6 +2,7 @@ package org.briarproject.crypto;
import org.briarproject.BriarTestCase; import org.briarproject.BriarTestCase;
import org.briarproject.TestSeedProvider; import org.briarproject.TestSeedProvider;
import org.briarproject.TestUtils;
import org.junit.Test; import org.junit.Test;
import java.util.Random; import java.util.Random;
@@ -18,9 +19,7 @@ public class PasswordBasedKdfTest extends BriarTestCase {
@Test @Test
public void testEncryptionAndDecryption() { public void testEncryptionAndDecryption() {
Random random = new Random(); byte[] input = TestUtils.getRandomBytes(1234);
byte[] input = new byte[1234];
random.nextBytes(input);
String password = "password"; String password = "password";
byte[] ciphertext = crypto.encryptWithPassword(input, password); byte[] ciphertext = crypto.encryptWithPassword(input, password);
byte[] output = crypto.decryptWithPassword(ciphertext, password); byte[] output = crypto.decryptWithPassword(ciphertext, password);
@@ -29,13 +28,11 @@ public class PasswordBasedKdfTest extends BriarTestCase {
@Test @Test
public void testInvalidCiphertextReturnsNull() { public void testInvalidCiphertextReturnsNull() {
Random random = new Random(); byte[] input = TestUtils.getRandomBytes(1234);
byte[] input = new byte[1234];
random.nextBytes(input);
String password = "password"; String password = "password";
byte[] ciphertext = crypto.encryptWithPassword(input, password); byte[] ciphertext = crypto.encryptWithPassword(input, password);
// Modify the ciphertext // Modify the ciphertext
int position = random.nextInt(ciphertext.length); int position = new Random().nextInt(ciphertext.length);
ciphertext[position] = (byte) (ciphertext[position] ^ 0xFF); ciphertext[position] = (byte) (ciphertext[position] ^ 0xFF);
byte[] output = crypto.decryptWithPassword(ciphertext, password); byte[] output = crypto.decryptWithPassword(ciphertext, password);
assertNull(output); assertNull(output);

View File

@@ -9,7 +9,6 @@ import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Random;
import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertEquals;
import static org.briarproject.api.transport.TransportConstants.FRAME_HEADER_LENGTH; import static org.briarproject.api.transport.TransportConstants.FRAME_HEADER_LENGTH;
@@ -18,22 +17,18 @@ import static org.briarproject.api.transport.TransportConstants.MAX_PAYLOAD_LENG
import static org.briarproject.api.transport.TransportConstants.STREAM_HEADER_IV_LENGTH; import static org.briarproject.api.transport.TransportConstants.STREAM_HEADER_IV_LENGTH;
import static org.briarproject.util.ByteUtils.INT_16_BYTES; import static org.briarproject.util.ByteUtils.INT_16_BYTES;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.fail;
public class StreamDecrypterImplTest extends BriarTestCase { public class StreamDecrypterImplTest extends BriarTestCase {
private final AuthenticatedCipher cipher; private final AuthenticatedCipher cipher;
private final SecretKey streamHeaderKey, frameKey; private final SecretKey streamHeaderKey, frameKey;
private final byte[] streamHeaderIv; private final byte[] streamHeaderIv;
private final Random random;
public StreamDecrypterImplTest() { public StreamDecrypterImplTest() {
cipher = new TestAuthenticatedCipher(); // Null cipher cipher = new TestAuthenticatedCipher(); // Null cipher
streamHeaderKey = TestUtils.createSecretKey(); streamHeaderKey = TestUtils.getSecretKey();
frameKey = TestUtils.createSecretKey(); frameKey = TestUtils.getSecretKey();
streamHeaderIv = new byte[STREAM_HEADER_IV_LENGTH]; streamHeaderIv = TestUtils.getRandomBytes(STREAM_HEADER_IV_LENGTH);
random = new Random();
random.nextBytes(streamHeaderIv);
} }
@Test @Test
@@ -42,15 +37,13 @@ public class StreamDecrypterImplTest extends BriarTestCase {
int payloadLength = 123, paddingLength = 234; int payloadLength = 123, paddingLength = 234;
FrameEncoder.encodeHeader(frameHeader, false, payloadLength, FrameEncoder.encodeHeader(frameHeader, false, payloadLength,
paddingLength); paddingLength);
byte[] payload = new byte[payloadLength]; byte[] payload = TestUtils.getRandomBytes(payloadLength);
random.nextBytes(payload);
byte[] frameHeader1 = new byte[FRAME_HEADER_LENGTH]; byte[] frameHeader1 = new byte[FRAME_HEADER_LENGTH];
int payloadLength1 = 345, paddingLength1 = 456; int payloadLength1 = 345, paddingLength1 = 456;
FrameEncoder.encodeHeader(frameHeader1, true, payloadLength1, FrameEncoder.encodeHeader(frameHeader1, true, payloadLength1,
paddingLength1); paddingLength1);
byte[] payload1 = new byte[payloadLength1]; byte[] payload1 = TestUtils.getRandomBytes(payloadLength1);
random.nextBytes(payload1);
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(streamHeaderIv); out.write(streamHeaderIv);
@@ -88,8 +81,7 @@ public class StreamDecrypterImplTest extends BriarTestCase {
int payloadLength = 123, paddingLength = 234; int payloadLength = 123, paddingLength = 234;
FrameEncoder.encodeHeader(frameHeader, false, payloadLength, FrameEncoder.encodeHeader(frameHeader, false, payloadLength,
paddingLength); paddingLength);
byte[] payload = new byte[payloadLength]; byte[] payload = TestUtils.getRandomBytes(payloadLength);
random.nextBytes(payload);
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(streamHeaderIv); out.write(streamHeaderIv);
out.write(frameKey.getBytes()); out.write(frameKey.getBytes());
@@ -116,8 +108,7 @@ public class StreamDecrypterImplTest extends BriarTestCase {
int payloadLength = MAX_PAYLOAD_LENGTH - 1, paddingLength = 2; int payloadLength = MAX_PAYLOAD_LENGTH - 1, paddingLength = 2;
ByteUtils.writeUint16(payloadLength, frameHeader, 0); ByteUtils.writeUint16(payloadLength, frameHeader, 0);
ByteUtils.writeUint16(paddingLength, frameHeader, INT_16_BYTES); ByteUtils.writeUint16(paddingLength, frameHeader, INT_16_BYTES);
byte[] payload = new byte[payloadLength]; byte[] payload = TestUtils.getRandomBytes(payloadLength);
random.nextBytes(payload);
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(streamHeaderIv); out.write(streamHeaderIv);
@@ -143,8 +134,7 @@ public class StreamDecrypterImplTest extends BriarTestCase {
int payloadLength = 123, paddingLength = 234; int payloadLength = 123, paddingLength = 234;
FrameEncoder.encodeHeader(frameHeader, false, payloadLength, FrameEncoder.encodeHeader(frameHeader, false, payloadLength,
paddingLength); paddingLength);
byte[] payload = new byte[payloadLength]; byte[] payload = TestUtils.getRandomBytes(payloadLength);
random.nextBytes(payload);
// Set one of the padding bytes non-zero // Set one of the padding bytes non-zero
byte[] padding = new byte[paddingLength]; byte[] padding = new byte[paddingLength];
padding[paddingLength - 1] = 1; padding[paddingLength - 1] = 1;
@@ -173,8 +163,7 @@ public class StreamDecrypterImplTest extends BriarTestCase {
int payloadLength = 123, paddingLength = 234; int payloadLength = 123, paddingLength = 234;
FrameEncoder.encodeHeader(frameHeader, true, payloadLength, FrameEncoder.encodeHeader(frameHeader, true, payloadLength,
paddingLength); paddingLength);
byte[] payload = new byte[payloadLength]; byte[] payload = TestUtils.getRandomBytes(payloadLength);
random.nextBytes(payload);
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(streamHeaderIv); out.write(streamHeaderIv);

View File

@@ -6,7 +6,6 @@ import org.briarproject.api.crypto.SecretKey;
import org.junit.Test; import org.junit.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.util.Random;
import static org.briarproject.api.transport.TransportConstants.FRAME_HEADER_LENGTH; import static org.briarproject.api.transport.TransportConstants.FRAME_HEADER_LENGTH;
import static org.briarproject.api.transport.TransportConstants.MAC_LENGTH; import static org.briarproject.api.transport.TransportConstants.MAC_LENGTH;
@@ -19,17 +18,13 @@ public class StreamEncrypterImplTest extends BriarTestCase {
private final AuthenticatedCipher cipher; private final AuthenticatedCipher cipher;
private final SecretKey streamHeaderKey, frameKey; private final SecretKey streamHeaderKey, frameKey;
private final byte[] tag, streamHeaderIv; private final byte[] tag, streamHeaderIv;
private final Random random;
public StreamEncrypterImplTest() { public StreamEncrypterImplTest() {
cipher = new TestAuthenticatedCipher(); // Null cipher cipher = new TestAuthenticatedCipher(); // Null cipher
streamHeaderKey = TestUtils.createSecretKey(); streamHeaderKey = TestUtils.getSecretKey();
frameKey = TestUtils.createSecretKey(); frameKey = TestUtils.getSecretKey();
tag = new byte[TAG_LENGTH]; tag = TestUtils.getRandomBytes(TAG_LENGTH);
streamHeaderIv = new byte[STREAM_HEADER_IV_LENGTH]; streamHeaderIv = TestUtils.getRandomBytes(STREAM_HEADER_IV_LENGTH);
random = new Random();
random.nextBytes(tag);
random.nextBytes(streamHeaderIv);
} }
@Test @Test
@@ -38,8 +33,7 @@ public class StreamEncrypterImplTest extends BriarTestCase {
StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, tag, StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, tag,
streamHeaderIv, streamHeaderKey, frameKey); streamHeaderIv, streamHeaderKey, frameKey);
int payloadLength = 123; int payloadLength = 123;
byte[] payload = new byte[payloadLength]; byte[] payload = TestUtils.getRandomBytes(payloadLength);
random.nextBytes(payload);
s.writeFrame(payload, payloadLength, 0, false); s.writeFrame(payload, payloadLength, 0, false);
@@ -64,8 +58,7 @@ public class StreamEncrypterImplTest extends BriarTestCase {
StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, tag, StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, tag,
streamHeaderIv, streamHeaderKey, frameKey); streamHeaderIv, streamHeaderKey, frameKey);
int payloadLength = 123; int payloadLength = 123;
byte[] payload = new byte[payloadLength]; byte[] payload = TestUtils.getRandomBytes(payloadLength);
random.nextBytes(payload);
s.writeFrame(payload, payloadLength, 0, true); s.writeFrame(payload, payloadLength, 0, true);
@@ -90,8 +83,7 @@ public class StreamEncrypterImplTest extends BriarTestCase {
StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, null, StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, null,
streamHeaderIv, streamHeaderKey, frameKey); streamHeaderIv, streamHeaderKey, frameKey);
int payloadLength = 123; int payloadLength = 123;
byte[] payload = new byte[payloadLength]; byte[] payload = TestUtils.getRandomBytes(payloadLength);
random.nextBytes(payload);
s.writeFrame(payload, payloadLength, 0, false); s.writeFrame(payload, payloadLength, 0, false);
@@ -115,8 +107,7 @@ public class StreamEncrypterImplTest extends BriarTestCase {
StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, null, StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, null,
streamHeaderIv, streamHeaderKey, frameKey); streamHeaderIv, streamHeaderKey, frameKey);
int payloadLength = 123; int payloadLength = 123;
byte[] payload = new byte[payloadLength]; byte[] payload = TestUtils.getRandomBytes(payloadLength);
random.nextBytes(payload);
s.writeFrame(payload, payloadLength, 0, true); s.writeFrame(payload, payloadLength, 0, true);
@@ -140,8 +131,7 @@ public class StreamEncrypterImplTest extends BriarTestCase {
StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, tag, StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, tag,
streamHeaderIv, streamHeaderKey, frameKey); streamHeaderIv, streamHeaderKey, frameKey);
int payloadLength = 123, paddingLength = 234; int payloadLength = 123, paddingLength = 234;
byte[] payload = new byte[payloadLength]; byte[] payload = TestUtils.getRandomBytes(payloadLength);
random.nextBytes(payload);
s.writeFrame(payload, payloadLength, paddingLength, false); s.writeFrame(payload, payloadLength, paddingLength, false);
@@ -168,8 +158,7 @@ public class StreamEncrypterImplTest extends BriarTestCase {
StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, tag, StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, tag,
streamHeaderIv, streamHeaderKey, frameKey); streamHeaderIv, streamHeaderKey, frameKey);
int payloadLength = 123, paddingLength = 234; int payloadLength = 123, paddingLength = 234;
byte[] payload = new byte[payloadLength]; byte[] payload = TestUtils.getRandomBytes(payloadLength);
random.nextBytes(payload);
s.writeFrame(payload, payloadLength, paddingLength, true); s.writeFrame(payload, payloadLength, paddingLength, true);
@@ -196,8 +185,7 @@ public class StreamEncrypterImplTest extends BriarTestCase {
StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, null, StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, null,
streamHeaderIv, streamHeaderKey, frameKey); streamHeaderIv, streamHeaderKey, frameKey);
int payloadLength = 123, paddingLength = 234; int payloadLength = 123, paddingLength = 234;
byte[] payload = new byte[payloadLength]; byte[] payload = TestUtils.getRandomBytes(payloadLength);
random.nextBytes(payload);
s.writeFrame(payload, payloadLength, paddingLength, false); s.writeFrame(payload, payloadLength, paddingLength, false);
@@ -223,8 +211,7 @@ public class StreamEncrypterImplTest extends BriarTestCase {
StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, null, StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, null,
streamHeaderIv, streamHeaderKey, frameKey); streamHeaderIv, streamHeaderKey, frameKey);
int payloadLength = 123, paddingLength = 234; int payloadLength = 123, paddingLength = 234;
byte[] payload = new byte[payloadLength]; byte[] payload = TestUtils.getRandomBytes(payloadLength);
random.nextBytes(payload);
s.writeFrame(payload, payloadLength, paddingLength, true); s.writeFrame(payload, payloadLength, paddingLength, true);
@@ -250,11 +237,9 @@ public class StreamEncrypterImplTest extends BriarTestCase {
StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, tag, StreamEncrypterImpl s = new StreamEncrypterImpl(out, cipher, tag,
streamHeaderIv, streamHeaderKey, frameKey); streamHeaderIv, streamHeaderKey, frameKey);
int payloadLength = 123, paddingLength = 234; int payloadLength = 123, paddingLength = 234;
byte[] payload = new byte[payloadLength]; byte[] payload = TestUtils.getRandomBytes(payloadLength);
random.nextBytes(payload);
int payloadLength1 = 345, paddingLength1 = 456; int payloadLength1 = 345, paddingLength1 = 456;
byte[] payload1 = new byte[payloadLength1]; byte[] payload1 = TestUtils.getRandomBytes(payloadLength1);
random.nextBytes(payload1);
s.writeFrame(payload, payloadLength, paddingLength, false); s.writeFrame(payload, payloadLength, paddingLength, false);
s.writeFrame(payload1, payloadLength1, paddingLength1, true); s.writeFrame(payload1, payloadLength1, paddingLength1, true);

View File

@@ -158,7 +158,7 @@ public class BdfReaderImplTest extends BriarTestCase {
@Test @Test
public void testReadString8() throws Exception { public void testReadString8() throws Exception {
String longest = TestUtils.createRandomString(Byte.MAX_VALUE); String longest = TestUtils.getRandomString(Byte.MAX_VALUE);
String longHex = StringUtils.toHexString(longest.getBytes("UTF-8")); String longHex = StringUtils.toHexString(longest.getBytes("UTF-8"));
// "foo", the empty string, and 127 random letters // "foo", the empty string, and 127 random letters
setContents("41" + "03" + "666F6F" + "41" + "00" + setContents("41" + "03" + "666F6F" + "41" + "00" +
@@ -180,7 +180,7 @@ public class BdfReaderImplTest extends BriarTestCase {
@Test @Test
public void testSkipString8() throws Exception { public void testSkipString8() throws Exception {
String longest = TestUtils.createRandomString(Byte.MAX_VALUE); String longest = TestUtils.getRandomString(Byte.MAX_VALUE);
String longHex = StringUtils.toHexString(longest.getBytes("UTF-8")); String longHex = StringUtils.toHexString(longest.getBytes("UTF-8"));
// "foo", the empty string, and 127 random letters // "foo", the empty string, and 127 random letters
setContents("41" + "03" + "666F6F" + "41" + "00" + setContents("41" + "03" + "666F6F" + "41" + "00" +
@@ -193,9 +193,9 @@ public class BdfReaderImplTest extends BriarTestCase {
@Test @Test
public void testReadString16() throws Exception { public void testReadString16() throws Exception {
String shortest = TestUtils.createRandomString(Byte.MAX_VALUE + 1); String shortest = TestUtils.getRandomString(Byte.MAX_VALUE + 1);
String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8")); String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8"));
String longest = TestUtils.createRandomString(Short.MAX_VALUE); String longest = TestUtils.getRandomString(Short.MAX_VALUE);
String longHex = StringUtils.toHexString(longest.getBytes("UTF-8")); String longHex = StringUtils.toHexString(longest.getBytes("UTF-8"));
// 128 random letters and 2^15 -1 random letters // 128 random letters and 2^15 -1 random letters
setContents("42" + "0080" + shortHex + "42" + "7FFF" + longHex); setContents("42" + "0080" + shortHex + "42" + "7FFF" + longHex);
@@ -206,7 +206,7 @@ public class BdfReaderImplTest extends BriarTestCase {
@Test(expected = FormatException.class) @Test(expected = FormatException.class)
public void testReadString16ChecksMaxLength() throws Exception { public void testReadString16ChecksMaxLength() throws Exception {
String shortest = TestUtils.createRandomString(Byte.MAX_VALUE + 1); String shortest = TestUtils.getRandomString(Byte.MAX_VALUE + 1);
String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8")); String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8"));
// 128 random letters, twice // 128 random letters, twice
setContents("42" + "0080" + shortHex + "42" + "0080" + shortHex); setContents("42" + "0080" + shortHex + "42" + "0080" + shortHex);
@@ -217,9 +217,9 @@ public class BdfReaderImplTest extends BriarTestCase {
@Test @Test
public void testSkipString16() throws Exception { public void testSkipString16() throws Exception {
String shortest = TestUtils.createRandomString(Byte.MAX_VALUE + 1); String shortest = TestUtils.getRandomString(Byte.MAX_VALUE + 1);
String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8")); String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8"));
String longest = TestUtils.createRandomString(Short.MAX_VALUE); String longest = TestUtils.getRandomString(Short.MAX_VALUE);
String longHex = StringUtils.toHexString(longest.getBytes("UTF-8")); String longHex = StringUtils.toHexString(longest.getBytes("UTF-8"));
// 128 random letters and 2^15 - 1 random letters // 128 random letters and 2^15 - 1 random letters
setContents("42" + "0080" + shortHex + "42" + "7FFF" + longHex); setContents("42" + "0080" + shortHex + "42" + "7FFF" + longHex);
@@ -230,7 +230,7 @@ public class BdfReaderImplTest extends BriarTestCase {
@Test @Test
public void testReadString32() throws Exception { public void testReadString32() throws Exception {
String shortest = TestUtils.createRandomString(Short.MAX_VALUE + 1); String shortest = TestUtils.getRandomString(Short.MAX_VALUE + 1);
String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8")); String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8"));
// 2^15 random letters // 2^15 random letters
setContents("44" + "00008000" + shortHex); setContents("44" + "00008000" + shortHex);
@@ -240,7 +240,7 @@ public class BdfReaderImplTest extends BriarTestCase {
@Test(expected = FormatException.class) @Test(expected = FormatException.class)
public void testReadString32ChecksMaxLength() throws Exception { public void testReadString32ChecksMaxLength() throws Exception {
String shortest = TestUtils.createRandomString(Short.MAX_VALUE + 1); String shortest = TestUtils.getRandomString(Short.MAX_VALUE + 1);
String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8")); String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8"));
// 2^15 random letters, twice // 2^15 random letters, twice
setContents("44" + "00008000" + shortHex + setContents("44" + "00008000" + shortHex +
@@ -252,7 +252,7 @@ public class BdfReaderImplTest extends BriarTestCase {
@Test @Test
public void testSkipString32() throws Exception { public void testSkipString32() throws Exception {
String shortest = TestUtils.createRandomString(Short.MAX_VALUE + 1); String shortest = TestUtils.getRandomString(Short.MAX_VALUE + 1);
String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8")); String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8"));
// 2^15 random letters, twice // 2^15 random letters, twice
setContents("44" + "00008000" + shortHex + setContents("44" + "00008000" + shortHex +

View File

@@ -81,7 +81,7 @@ public class BdfWriterImplTest extends BriarTestCase {
@Test @Test
public void testWriteString8() throws IOException { public void testWriteString8() throws IOException {
String longest = TestUtils.createRandomString(Byte.MAX_VALUE); String longest = TestUtils.getRandomString(Byte.MAX_VALUE);
String longHex = StringUtils.toHexString(longest.getBytes("UTF-8")); String longHex = StringUtils.toHexString(longest.getBytes("UTF-8"));
w.writeString("foo bar baz bam "); w.writeString("foo bar baz bam ");
w.writeString(longest); w.writeString(longest);
@@ -93,9 +93,9 @@ public class BdfWriterImplTest extends BriarTestCase {
@Test @Test
public void testWriteString16() throws IOException { public void testWriteString16() throws IOException {
String shortest = TestUtils.createRandomString(Byte.MAX_VALUE + 1); String shortest = TestUtils.getRandomString(Byte.MAX_VALUE + 1);
String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8")); String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8"));
String longest = TestUtils.createRandomString(Short.MAX_VALUE); String longest = TestUtils.getRandomString(Short.MAX_VALUE);
String longHex = StringUtils.toHexString(longest.getBytes("UTF-8")); String longHex = StringUtils.toHexString(longest.getBytes("UTF-8"));
w.writeString(shortest); w.writeString(shortest);
w.writeString(longest); w.writeString(longest);
@@ -106,7 +106,7 @@ public class BdfWriterImplTest extends BriarTestCase {
@Test @Test
public void testWriteString32() throws IOException { public void testWriteString32() throws IOException {
String shortest = TestUtils.createRandomString(Short.MAX_VALUE + 1); String shortest = TestUtils.getRandomString(Short.MAX_VALUE + 1);
String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8")); String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8"));
w.writeString(shortest); w.writeString(shortest);
// STRING_32 tag, length 2^15, UTF-8 bytes // STRING_32 tag, length 2^15, UTF-8 bytes

View File

@@ -15,7 +15,7 @@ import java.util.Map;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
public class MetadataEncoderParserImplTest extends BriarTestCase { public class MetadataEncoderParserIntegrationTest extends BriarTestCase {
MetadataEncoderImpl e; MetadataEncoderImpl e;
MetadataParserImpl p; MetadataParserImpl p;

View File

@@ -15,7 +15,6 @@ import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Random;
import static java.sql.Types.BINARY; import static java.sql.Types.BINARY;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@@ -48,10 +47,9 @@ public class BasicH2Test extends BriarTestCase {
// Create the table // Create the table
createTable(connection); createTable(connection);
// Generate an ID and two names // Generate an ID and two names
byte[] id = new byte[32]; byte[] id = TestUtils.getRandomId();
new Random().nextBytes(id); String oldName = TestUtils.getRandomString(50);
String oldName = TestUtils.createRandomString(50); String newName = TestUtils.getRandomString(50);
String newName = TestUtils.createRandomString(50);
// Insert the ID and old name into the table // Insert the ID and old name into the table
insertRow(id, oldName); insertRow(id, oldName);
// Check that the old name can be retrieved using the ID // Check that the old name can be retrieved using the ID
@@ -75,14 +73,13 @@ public class BasicH2Test extends BriarTestCase {
// Create the table // Create the table
createTable(connection); createTable(connection);
// Generate some IDs and two sets of names // Generate some IDs and two sets of names
byte[][] ids = new byte[BATCH_SIZE][32]; byte[][] ids = new byte[BATCH_SIZE][];
String[] oldNames = new String[BATCH_SIZE]; String[] oldNames = new String[BATCH_SIZE];
String[] newNames = new String[BATCH_SIZE]; String[] newNames = new String[BATCH_SIZE];
Random random = new Random();
for (int i = 0; i < BATCH_SIZE; i++) { for (int i = 0; i < BATCH_SIZE; i++) {
random.nextBytes(ids[i]); ids[i] = TestUtils.getRandomId();
oldNames[i] = TestUtils.createRandomString(50); oldNames[i] = TestUtils.getRandomString(50);
newNames[i] = TestUtils.createRandomString(50); newNames[i] = TestUtils.getRandomString(50);
} }
// Insert the IDs and old names into the table as a batch // Insert the IDs and old names into the table as a batch
insertBatch(ids, oldNames); insertBatch(ids, oldNames);

View File

@@ -1382,20 +1382,20 @@ public class DatabaseComponentImplTest extends BriarTestCase {
} }
private TransportKeys createTransportKeys() { private TransportKeys createTransportKeys() {
SecretKey inPrevTagKey = TestUtils.createSecretKey(); SecretKey inPrevTagKey = TestUtils.getSecretKey();
SecretKey inPrevHeaderKey = TestUtils.createSecretKey(); SecretKey inPrevHeaderKey = TestUtils.getSecretKey();
IncomingKeys inPrev = new IncomingKeys(inPrevTagKey, inPrevHeaderKey, IncomingKeys inPrev = new IncomingKeys(inPrevTagKey, inPrevHeaderKey,
1, 123, new byte[4]); 1, 123, new byte[4]);
SecretKey inCurrTagKey = TestUtils.createSecretKey(); SecretKey inCurrTagKey = TestUtils.getSecretKey();
SecretKey inCurrHeaderKey = TestUtils.createSecretKey(); SecretKey inCurrHeaderKey = TestUtils.getSecretKey();
IncomingKeys inCurr = new IncomingKeys(inCurrTagKey, inCurrHeaderKey, IncomingKeys inCurr = new IncomingKeys(inCurrTagKey, inCurrHeaderKey,
2, 234, new byte[4]); 2, 234, new byte[4]);
SecretKey inNextTagKey = TestUtils.createSecretKey(); SecretKey inNextTagKey = TestUtils.getSecretKey();
SecretKey inNextHeaderKey = TestUtils.createSecretKey(); SecretKey inNextHeaderKey = TestUtils.getSecretKey();
IncomingKeys inNext = new IncomingKeys(inNextTagKey, inNextHeaderKey, IncomingKeys inNext = new IncomingKeys(inNextTagKey, inNextHeaderKey,
3, 345, new byte[4]); 3, 345, new byte[4]);
SecretKey outCurrTagKey = TestUtils.createSecretKey(); SecretKey outCurrTagKey = TestUtils.getSecretKey();
SecretKey outCurrHeaderKey = TestUtils.createSecretKey(); SecretKey outCurrHeaderKey = TestUtils.getSecretKey();
OutgoingKeys outCurr = new OutgoingKeys(outCurrTagKey, outCurrHeaderKey, OutgoingKeys outCurr = new OutgoingKeys(outCurrTagKey, outCurrHeaderKey,
2, 456); 2, 456);
return new TransportKeys(transportId, inPrev, inCurr, inNext, outCurr); return new TransportKeys(transportId, inPrev, inCurr, inNext, outCurr);

View File

@@ -63,7 +63,6 @@ public class H2DatabaseTest extends BriarTestCase {
private static final int MAX_SIZE = 5 * ONE_MEGABYTE; private static final int MAX_SIZE = 5 * ONE_MEGABYTE;
private final File testDir = TestUtils.getTestDirectory(); private final File testDir = TestUtils.getTestDirectory();
private final Random random = new Random();
private final GroupId groupId; private final GroupId groupId;
private final Group group; private final Group group;
private final Author author; private final Author author;
@@ -90,8 +89,7 @@ public class H2DatabaseTest extends BriarTestCase {
new byte[MAX_PUBLIC_KEY_LENGTH], new byte[123], timestamp); new byte[MAX_PUBLIC_KEY_LENGTH], new byte[123], timestamp);
messageId = new MessageId(TestUtils.getRandomId()); messageId = new MessageId(TestUtils.getRandomId());
size = 1234; size = 1234;
raw = new byte[size]; raw = TestUtils.getRandomBytes(size);
random.nextBytes(raw);
message = new Message(messageId, groupId, timestamp, raw); message = new Message(messageId, groupId, timestamp, raw);
transportId = new TransportId("id"); transportId = new TransportId("id");
contactId = new ContactId(1); contactId = new ContactId(1);
@@ -747,7 +745,7 @@ public class H2DatabaseTest extends BriarTestCase {
db.updateTransportKeys(txn, Collections.singletonMap(contactId, keys)); db.updateTransportKeys(txn, Collections.singletonMap(contactId, keys));
// Update the reordering window and retrieve the transport keys // Update the reordering window and retrieve the transport keys
random.nextBytes(bitmap); new Random().nextBytes(bitmap);
db.setReorderingWindow(txn, contactId, transportId, rotationPeriod, db.setReorderingWindow(txn, contactId, transportId, rotationPeriod,
base + 1, bitmap); base + 1, bitmap);
Map<ContactId, TransportKeys> newKeys = Map<ContactId, TransportKeys> newKeys =
@@ -1166,20 +1164,20 @@ public class H2DatabaseTest extends BriarTestCase {
} }
private TransportKeys createTransportKeys() { private TransportKeys createTransportKeys() {
SecretKey inPrevTagKey = TestUtils.createSecretKey(); SecretKey inPrevTagKey = TestUtils.getSecretKey();
SecretKey inPrevHeaderKey = TestUtils.createSecretKey(); SecretKey inPrevHeaderKey = TestUtils.getSecretKey();
IncomingKeys inPrev = new IncomingKeys(inPrevTagKey, inPrevHeaderKey, IncomingKeys inPrev = new IncomingKeys(inPrevTagKey, inPrevHeaderKey,
1, 123, new byte[4]); 1, 123, new byte[4]);
SecretKey inCurrTagKey = TestUtils.createSecretKey(); SecretKey inCurrTagKey = TestUtils.getSecretKey();
SecretKey inCurrHeaderKey = TestUtils.createSecretKey(); SecretKey inCurrHeaderKey = TestUtils.getSecretKey();
IncomingKeys inCurr = new IncomingKeys(inCurrTagKey, inCurrHeaderKey, IncomingKeys inCurr = new IncomingKeys(inCurrTagKey, inCurrHeaderKey,
2, 234, new byte[4]); 2, 234, new byte[4]);
SecretKey inNextTagKey = TestUtils.createSecretKey(); SecretKey inNextTagKey = TestUtils.getSecretKey();
SecretKey inNextHeaderKey = TestUtils.createSecretKey(); SecretKey inNextHeaderKey = TestUtils.getSecretKey();
IncomingKeys inNext = new IncomingKeys(inNextTagKey, inNextHeaderKey, IncomingKeys inNext = new IncomingKeys(inNextTagKey, inNextHeaderKey,
3, 345, new byte[4]); 3, 345, new byte[4]);
SecretKey outCurrTagKey = TestUtils.createSecretKey(); SecretKey outCurrTagKey = TestUtils.getSecretKey();
SecretKey outCurrHeaderKey = TestUtils.createSecretKey(); SecretKey outCurrHeaderKey = TestUtils.getSecretKey();
OutgoingKeys outCurr = new OutgoingKeys(outCurrTagKey, outCurrHeaderKey, OutgoingKeys outCurr = new OutgoingKeys(outCurrTagKey, outCurrHeaderKey,
2, 456); 2, 456);
return new TransportKeys(transportId, inPrev, inCurr, inNext, outCurr); return new TransportKeys(transportId, inPrev, inCurr, inNext, outCurr);

View File

@@ -8,7 +8,6 @@ import org.briarproject.api.crypto.PublicKey;
import org.briarproject.api.crypto.SecretKey; import org.briarproject.api.crypto.SecretKey;
import org.briarproject.api.keyagreement.Payload; import org.briarproject.api.keyagreement.Payload;
import org.briarproject.api.keyagreement.PayloadEncoder; import org.briarproject.api.keyagreement.PayloadEncoder;
import org.briarproject.util.StringUtils;
import org.jmock.Expectations; import org.jmock.Expectations;
import org.jmock.auto.Mock; import org.jmock.auto.Mock;
import org.jmock.integration.junit4.JUnitRuleMockery; import org.jmock.integration.junit4.JUnitRuleMockery;
@@ -69,8 +68,8 @@ public class KeyAgreementProtocolTest extends BriarTestCase {
final Payload theirPayload = new Payload(BOB_COMMIT, null); final Payload theirPayload = new Payload(BOB_COMMIT, null);
final Payload ourPayload = new Payload(ALICE_COMMIT, null); final Payload ourPayload = new Payload(ALICE_COMMIT, null);
final KeyPair ourKeyPair = new KeyPair(ourPubKey, null); final KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
final SecretKey sharedSecret = TestUtils.createSecretKey(); final SecretKey sharedSecret = TestUtils.getSecretKey();
final SecretKey masterSecret = TestUtils.createSecretKey(); final SecretKey masterSecret = TestUtils.getSecretKey();
KeyAgreementProtocol protocol = KeyAgreementProtocol protocol =
new KeyAgreementProtocol(callbacks, crypto, payloadEncoder, new KeyAgreementProtocol(callbacks, crypto, payloadEncoder,
@@ -133,8 +132,8 @@ public class KeyAgreementProtocolTest extends BriarTestCase {
final Payload theirPayload = new Payload(ALICE_COMMIT, null); final Payload theirPayload = new Payload(ALICE_COMMIT, null);
final Payload ourPayload = new Payload(BOB_COMMIT, null); final Payload ourPayload = new Payload(BOB_COMMIT, null);
final KeyPair ourKeyPair = new KeyPair(ourPubKey, null); final KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
final SecretKey sharedSecret = TestUtils.createSecretKey(); final SecretKey sharedSecret = TestUtils.getSecretKey();
final SecretKey masterSecret = TestUtils.createSecretKey(); final SecretKey masterSecret = TestUtils.getSecretKey();
KeyAgreementProtocol protocol = KeyAgreementProtocol protocol =
new KeyAgreementProtocol(callbacks, crypto, payloadEncoder, new KeyAgreementProtocol(callbacks, crypto, payloadEncoder,
@@ -274,7 +273,7 @@ public class KeyAgreementProtocolTest extends BriarTestCase {
final Payload theirPayload = new Payload(BOB_COMMIT, null); final Payload theirPayload = new Payload(BOB_COMMIT, null);
final Payload ourPayload = new Payload(ALICE_COMMIT, null); final Payload ourPayload = new Payload(ALICE_COMMIT, null);
final KeyPair ourKeyPair = new KeyPair(ourPubKey, null); final KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
final SecretKey sharedSecret = TestUtils.createSecretKey(); final SecretKey sharedSecret = TestUtils.getSecretKey();
KeyAgreementProtocol protocol = KeyAgreementProtocol protocol =
new KeyAgreementProtocol(callbacks, crypto, payloadEncoder, new KeyAgreementProtocol(callbacks, crypto, payloadEncoder,
@@ -339,7 +338,7 @@ public class KeyAgreementProtocolTest extends BriarTestCase {
final Payload theirPayload = new Payload(ALICE_COMMIT, null); final Payload theirPayload = new Payload(ALICE_COMMIT, null);
final Payload ourPayload = new Payload(BOB_COMMIT, null); final Payload ourPayload = new Payload(BOB_COMMIT, null);
final KeyPair ourKeyPair = new KeyPair(ourPubKey, null); final KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
final SecretKey sharedSecret = TestUtils.createSecretKey(); final SecretKey sharedSecret = TestUtils.getSecretKey();
KeyAgreementProtocol protocol = KeyAgreementProtocol protocol =
new KeyAgreementProtocol(callbacks, crypto, payloadEncoder, new KeyAgreementProtocol(callbacks, crypto, payloadEncoder,

View File

@@ -118,7 +118,7 @@ public class TransportPropertyValidatorTest extends BriarTestCase {
/* Generate a string or arbitrary length for the transport id*/ /* Generate a string or arbitrary length for the transport id*/
String wrongTransportIdString = String wrongTransportIdString =
TestUtils.createRandomString(MAX_TRANSPORT_ID_LENGTH + 1); TestUtils.getRandomString(MAX_TRANSPORT_ID_LENGTH + 1);
BdfList body = BdfList.of(deviceId, wrongTransportIdString, 4, BdfList body = BdfList.of(deviceId, wrongTransportIdString, 4,
bdfDictionary); bdfDictionary);
tpv.validateMessage(message, group, body); tpv.validateMessage(message, group, body);

View File

@@ -11,7 +11,6 @@ import org.junit.Test;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.util.HashSet; import java.util.HashSet;
import java.util.Random;
import java.util.Set; import java.util.Set;
import static org.briarproject.api.system.SeedProvider.SEED_BYTES; import static org.briarproject.api.system.SeedProvider.SEED_BYTES;
@@ -68,8 +67,7 @@ public class LinuxSeedProviderTest extends BriarTestCase {
return; return;
} }
// Generate a seed // Generate a seed
byte[] seed = new byte[SEED_BYTES]; byte[] seed = TestUtils.getRandomBytes(SEED_BYTES);
new Random().nextBytes(seed);
// Write the seed to a file // Write the seed to a file
File urandom = new File(testDir, "urandom"); File urandom = new File(testDir, "urandom");
urandom.delete(); urandom.delete();

View File

@@ -1,12 +1,12 @@
package org.briarproject.transport; package org.briarproject.transport;
import org.briarproject.BriarTestCase; import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.transport.ReorderingWindow.Change; import org.briarproject.transport.ReorderingWindow.Change;
import org.junit.Test; import org.junit.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Random;
import static org.briarproject.api.transport.TransportConstants.REORDERING_WINDOW_SIZE; import static org.briarproject.api.transport.TransportConstants.REORDERING_WINDOW_SIZE;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
@@ -14,12 +14,12 @@ import static org.junit.Assert.assertEquals;
public class ReorderingWindowTest extends BriarTestCase { public class ReorderingWindowTest extends BriarTestCase {
private static final int BITMAP_BYTES = REORDERING_WINDOW_SIZE / 8;
@Test @Test
public void testBitmapConversion() { public void testBitmapConversion() {
Random random = new Random();
byte[] bitmap = new byte[REORDERING_WINDOW_SIZE / 8];
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
random.nextBytes(bitmap); byte[] bitmap = TestUtils.getRandomBytes(BITMAP_BYTES);
ReorderingWindow window = new ReorderingWindow(0L, bitmap); ReorderingWindow window = new ReorderingWindow(0L, bitmap);
assertArrayEquals(bitmap, window.getBitmap()); assertArrayEquals(bitmap, window.getBitmap());
} }
@@ -27,7 +27,7 @@ public class ReorderingWindowTest extends BriarTestCase {
@Test @Test
public void testWindowSlidesWhenFirstElementIsSeen() { public void testWindowSlidesWhenFirstElementIsSeen() {
byte[] bitmap = new byte[REORDERING_WINDOW_SIZE / 8]; byte[] bitmap = new byte[BITMAP_BYTES];
ReorderingWindow window = new ReorderingWindow(0L, bitmap); ReorderingWindow window = new ReorderingWindow(0L, bitmap);
// Set the first element seen // Set the first element seen
Change change = window.setSeen(0L); Change change = window.setSeen(0L);
@@ -42,7 +42,7 @@ public class ReorderingWindowTest extends BriarTestCase {
@Test @Test
public void testWindowDoesNotSlideWhenElementBelowMidpointIsSeen() { public void testWindowDoesNotSlideWhenElementBelowMidpointIsSeen() {
byte[] bitmap = new byte[REORDERING_WINDOW_SIZE / 8]; byte[] bitmap = new byte[BITMAP_BYTES];
ReorderingWindow window = new ReorderingWindow(0L, bitmap); ReorderingWindow window = new ReorderingWindow(0L, bitmap);
// Set an element below the midpoint seen // Set an element below the midpoint seen
Change change = window.setSeen(1L); Change change = window.setSeen(1L);
@@ -57,7 +57,7 @@ public class ReorderingWindowTest extends BriarTestCase {
@Test @Test
public void testWindowSlidesWhenElementAboveMidpointIsSeen() { public void testWindowSlidesWhenElementAboveMidpointIsSeen() {
byte[] bitmap = new byte[REORDERING_WINDOW_SIZE / 8]; byte[] bitmap = new byte[BITMAP_BYTES];
ReorderingWindow window = new ReorderingWindow(0, bitmap); ReorderingWindow window = new ReorderingWindow(0, bitmap);
long aboveMidpoint = REORDERING_WINDOW_SIZE / 2; long aboveMidpoint = REORDERING_WINDOW_SIZE / 2;
// Set an element above the midpoint seen // Set an element above the midpoint seen
@@ -74,7 +74,7 @@ public class ReorderingWindowTest extends BriarTestCase {
@Test @Test
public void testWindowSlidesUntilLowestElementIsUnseenWhenFirstElementIsSeen() { public void testWindowSlidesUntilLowestElementIsUnseenWhenFirstElementIsSeen() {
byte[] bitmap = new byte[REORDERING_WINDOW_SIZE / 8]; byte[] bitmap = new byte[BITMAP_BYTES];
ReorderingWindow window = new ReorderingWindow(0L, bitmap); ReorderingWindow window = new ReorderingWindow(0L, bitmap);
window.setSeen(1L); window.setSeen(1L);
// Set the first element seen // Set the first element seen
@@ -90,7 +90,7 @@ public class ReorderingWindowTest extends BriarTestCase {
@Test @Test
public void testWindowSlidesUntilLowestElementIsUnseenWhenElementAboveMidpointIsSeen() { public void testWindowSlidesUntilLowestElementIsUnseenWhenElementAboveMidpointIsSeen() {
byte[] bitmap = new byte[REORDERING_WINDOW_SIZE / 8]; byte[] bitmap = new byte[BITMAP_BYTES];
ReorderingWindow window = new ReorderingWindow(0L, bitmap); ReorderingWindow window = new ReorderingWindow(0L, bitmap);
window.setSeen(1L); window.setSeen(1L);
long aboveMidpoint = REORDERING_WINDOW_SIZE / 2; long aboveMidpoint = REORDERING_WINDOW_SIZE / 2;

View File

@@ -1,6 +1,7 @@
package org.briarproject.transport; package org.briarproject.transport;
import org.briarproject.BriarTestCase; import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.api.crypto.StreamDecrypter; import org.briarproject.api.crypto.StreamDecrypter;
import org.briarproject.api.crypto.StreamEncrypter; import org.briarproject.api.crypto.StreamEncrypter;
import org.junit.Test; import org.junit.Test;
@@ -10,7 +11,6 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Random;
import static org.briarproject.api.transport.TransportConstants.FRAME_HEADER_LENGTH; import static org.briarproject.api.transport.TransportConstants.FRAME_HEADER_LENGTH;
import static org.briarproject.api.transport.TransportConstants.MAC_LENGTH; import static org.briarproject.api.transport.TransportConstants.MAC_LENGTH;
@@ -19,20 +19,15 @@ import static org.briarproject.api.transport.TransportConstants.TAG_LENGTH;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
public class TransportIntegrationTest extends BriarTestCase { public class StreamReaderWriterIntegrationTest extends BriarTestCase {
private final Random random = new Random();
@Test @Test
public void testWriteAndRead() throws Exception { public void testWriteAndRead() throws Exception {
// Generate a random tag // Generate a random tag
byte[] tag = new byte[TAG_LENGTH]; byte[] tag = TestUtils.getRandomBytes(TAG_LENGTH);
random.nextBytes(tag);
// Generate two frames with random payloads // Generate two frames with random payloads
byte[] payload1 = new byte[123]; byte[] payload1 = TestUtils.getRandomBytes(123);
random.nextBytes(payload1); byte[] payload2 = TestUtils.getRandomBytes(321);
byte[] payload2 = new byte[321];
random.nextBytes(payload2);
// Write the tag and the frames // Write the tag and the frames
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
StreamEncrypter encrypter = new TestStreamEncrypter(out, tag); StreamEncrypter encrypter = new TestStreamEncrypter(out, tag);

View File

@@ -46,9 +46,9 @@ public class TransportKeyManagerTest extends BriarTestCase {
private final long rotationPeriodLength = maxLatency + MAX_CLOCK_DIFFERENCE; private final long rotationPeriodLength = maxLatency + MAX_CLOCK_DIFFERENCE;
private final ContactId contactId = new ContactId(123); private final ContactId contactId = new ContactId(123);
private final ContactId contactId1 = new ContactId(234); private final ContactId contactId1 = new ContactId(234);
private final SecretKey tagKey = TestUtils.createSecretKey(); private final SecretKey tagKey = TestUtils.getSecretKey();
private final SecretKey headerKey = TestUtils.createSecretKey(); private final SecretKey headerKey = TestUtils.getSecretKey();
private final SecretKey masterKey = TestUtils.createSecretKey(); private final SecretKey masterKey = TestUtils.getSecretKey();
private final Random random = new Random(); private final Random random = new Random();
@Test @Test