From 27ba2a91646dca83bac69c9ed2948c4cb1bc1acc Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 13 Nov 2018 14:50:39 +0100 Subject: [PATCH] Improve crypto test: create a helper. Also improve callbacks. --- .../androidsdk/common/CommonTestHelper.java | 4 +- .../androidsdk/common/CryptoTestData.kt | 32 + .../androidsdk/common/CryptoTestHelper.kt | 373 ++++++++ .../androidsdk/common/TestApiCallback.java | 68 -- .../androidsdk/common/TestApiCallback.kt | 73 ++ .../androidsdk/common/TestConstants.java | 18 +- .../androidsdk/crypto/CryptoRestTest.java | 2 +- .../crypto/CryptoStoreMigrationTest.kt | 207 +--- .../matrix/androidsdk/crypto/CryptoTest.java | 902 +++++------------- .../java/org/matrix/androidsdk/MXSession.java | 3 +- .../androidsdk/crypto/CryptoConstants.kt | 32 + .../matrix/androidsdk/crypto/MXCrypto.java | 6 +- .../androidsdk/crypto/MXCryptoAlgorithms.java | 18 +- .../matrix/androidsdk/crypto/MXOlmDevice.java | 4 +- .../algorithms/megolm/MXMegolmEncryption.java | 6 +- .../data/MXOlmInboundGroupSession2.java | 6 +- .../org/matrix/androidsdk/data/RoomState.java | 2 +- .../data/cryptostore/IMXCryptoStore.java | 1 + .../rest/callback/ApiFailureCallback.java | 17 +- .../rest/callback/ErrorCallback.java | 30 + .../rest/callback/SuccessErrorCallback.kt | 19 + 21 files changed, 876 insertions(+), 947 deletions(-) create mode 100644 matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/CryptoTestData.kt create mode 100644 matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/CryptoTestHelper.kt delete mode 100644 matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/TestApiCallback.java create mode 100644 matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/TestApiCallback.kt create mode 100644 matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/CryptoConstants.kt create mode 100644 matrix-sdk/src/main/java/org/matrix/androidsdk/rest/callback/ErrorCallback.java create mode 100644 matrix-sdk/src/main/java/org/matrix/androidsdk/rest/callback/SuccessErrorCallback.kt diff --git a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/CommonTestHelper.java b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/CommonTestHelper.java index 337e2b708..3ee7d76be 100644 --- a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/CommonTestHelper.java +++ b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/CommonTestHelper.java @@ -224,7 +224,7 @@ private MXSession createAccountAndSync(Context context, CountDownLatch lock = new CountDownLatch(1); // get the registration session id - loginRestClient.register(registrationParams, new TestApiCallback(lock) { + loginRestClient.register(registrationParams, new TestApiCallback(lock, false) { @Override public void onMatrixError(MatrixError e) { // detect if a parameter is expected @@ -356,7 +356,7 @@ public void onSuccess(Credentials credentials) { * @throws InterruptedException */ public void await(CountDownLatch latch) throws InterruptedException { - Assert.assertTrue(latch.await(TestConstants.AWAIT_TIME_OUT_MILLIS, TimeUnit.MILLISECONDS)); + Assert.assertTrue(latch.await(TestConstants.getTimeOutMillis(), TimeUnit.MILLISECONDS)); } /** diff --git a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/CryptoTestData.kt b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/CryptoTestData.kt new file mode 100644 index 000000000..5ef602a2b --- /dev/null +++ b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/CryptoTestData.kt @@ -0,0 +1,32 @@ +/* + * Copyright 2018 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.androidsdk.common + +import android.content.Context +import org.matrix.androidsdk.MXSession + +data class CryptoTestData(val firstSession: MXSession, + val roomId: String, + val secondSession: MXSession? = null, + val thirdSession: MXSession? = null) { + + fun clear(context: Context) { + firstSession.clear(context) + secondSession?.clear(context) + secondSession?.clear(context) + } +} diff --git a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/CryptoTestHelper.kt b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/CryptoTestHelper.kt new file mode 100644 index 000000000..8cbb72334 --- /dev/null +++ b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/CryptoTestHelper.kt @@ -0,0 +1,373 @@ +/* + * Copyright 2018 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.androidsdk.common + +import android.os.SystemClock +import android.text.TextUtils +import org.junit.Assert +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.matrix.androidsdk.MXSession +import org.matrix.androidsdk.crypto.MXCRYPTO_ALGORITHM_MEGOLM +import org.matrix.androidsdk.crypto.MXCryptoAlgorithms +import org.matrix.androidsdk.data.RoomState +import org.matrix.androidsdk.listeners.MXEventListener +import org.matrix.androidsdk.rest.model.Event +import org.matrix.androidsdk.rest.model.RoomMember +import org.matrix.androidsdk.rest.model.message.Message +import org.matrix.androidsdk.util.JsonUtils +import java.util.* +import java.util.concurrent.CountDownLatch + +/** + * Synchronously enable crypto for the session and fail if it does not work + */ +fun MXSession.enableCrypto() { + val cryptoLatch = CountDownLatch(1) + enableCrypto(true, TestApiCallback(cryptoLatch)) + cryptoLatch.await() +} + + +class CryptoTestHelper(val mTestHelper: CommonTestHelper) { + + val messagesFromAlice: List = Arrays.asList("0 - Hello I'm Alice!", "4 - Go!") + val messagesFromBob: List = Arrays.asList("1 - Hello I'm Bob!", "2 - Isn't life grand?", "3 - Let's go to the opera.") + + // Set this value to false to test the new Realm store and to true to test legacy Filestore + val USE_LEGACY_CRYPTO_STORE = false + + // Lazy loading is on by default now + private val LAZY_LOADING_ENABLED = true + + val defaultSessionParams = SessionTestParams(true, false, LAZY_LOADING_ENABLED, USE_LEGACY_CRYPTO_STORE) + val encryptedSessionParams = SessionTestParams(true, true, LAZY_LOADING_ENABLED, USE_LEGACY_CRYPTO_STORE) + + fun buildTextEvent(text: String, session: MXSession, roomId: String): Event { + val message = Message() + message.msgtype = Message.MSGTYPE_TEXT + message.body = text + + return Event(message, session.credentials.userId, roomId) + } + + /** + * @return alice session + */ + fun doE2ETestWithAliceInARoom(): CryptoTestData { + val results = HashMap() + val aliceSession = mTestHelper.createAccount(TestConstants.USER_ALICE, defaultSessionParams) + val lock0 = CountDownLatch(1) + + aliceSession.enableCrypto(true, object : TestApiCallback(lock0) { + override fun onSuccess(info: Void?) { + results["enableCrypto"] = "enableCrypto" + super.onSuccess(info) + } + }) + mTestHelper.await(lock0) + Assert.assertTrue(results.containsKey("enableCrypto")) + + var roomId: String? = null + val lock1 = CountDownLatch(1) + + aliceSession.createRoom(object : TestApiCallback(lock1) { + override fun onSuccess(info: String) { + roomId = info + super.onSuccess(info) + } + }) + + mTestHelper.await(lock1) + Assert.assertNotNull(roomId) + + val room = aliceSession.dataHandler.getRoom(roomId) + + val lock2 = CountDownLatch(1) + room.enableEncryptionWithAlgorithm(MXCRYPTO_ALGORITHM_MEGOLM, object : TestApiCallback(lock2) { + override fun onSuccess(info: Void?) { + results["enableEncryptionWithAlgorithm"] = "enableEncryptionWithAlgorithm" + super.onSuccess(info) + } + }) + mTestHelper.await(lock2) + Assert.assertTrue(results.containsKey("enableEncryptionWithAlgorithm")) + + return CryptoTestData(aliceSession, roomId!!) + } + + /** + * @param cryptedBob + * @return alice and bob sessions + */ + fun doE2ETestWithAliceAndBobInARoom(cryptedBob: Boolean): CryptoTestData { + val statuses = HashMap() + + val cryptoTestData = doE2ETestWithAliceInARoom() + val aliceSession = cryptoTestData.firstSession + val aliceRoomId = cryptoTestData.roomId + + val room = aliceSession.dataHandler.getRoom(aliceRoomId) + + val bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams) + val lock0 = CountDownLatch(1) + + bobSession.enableCrypto(cryptedBob, object : TestApiCallback(lock0) { + override fun onSuccess(info: Void?) { + statuses["enableCrypto"] = "enableCrypto" + super.onSuccess(info) + } + }) + mTestHelper.await(lock0) + + val lock1 = CountDownLatch(2) + + val bobEventListener = object : MXEventListener() { + override fun onNewRoom(roomId: String) { + if (TextUtils.equals(roomId, aliceRoomId)) { + if (!statuses.containsKey("onNewRoom")) { + statuses["onNewRoom"] = "onNewRoom" + lock1.countDown() + } + } + } + } + + bobSession.dataHandler.addListener(bobEventListener) + + room.invite(bobSession.myUserId, object : TestApiCallback(lock1) { + override fun onSuccess(info: Void?) { + statuses["invite"] = "invite" + super.onSuccess(info) + } + }) + + mTestHelper.await(lock1) + + Assert.assertTrue(statuses.containsKey("invite") && statuses.containsKey("onNewRoom")) + + bobSession.dataHandler.removeListener(bobEventListener) + + val lock2 = CountDownLatch(2) + + bobSession.joinRoom(aliceRoomId, TestApiCallback(lock2)) + + room.addEventListener(object : MXEventListener() { + override fun onLiveEvent(event: Event, roomState: RoomState) { + if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_STATE_ROOM_MEMBER)) { + val contentToConsider = event.contentAsJsonObject + val member = JsonUtils.toRoomMember(contentToConsider) + + if (TextUtils.equals(member.membership, RoomMember.MEMBERSHIP_JOIN)) { + statuses["AliceJoin"] = "AliceJoin" + lock2.countDown() + } + } + } + }) + + mTestHelper.await(lock2) + + // Ensure bob can send messages to the room + val roomFromBobPOV = bobSession.getDataHandler().getRoom(aliceRoomId) + assertNotNull(roomFromBobPOV.getState().getPowerLevels()) + assertTrue(roomFromBobPOV.getState().getPowerLevels().maySendMessage(bobSession.getMyUserId())) + + Assert.assertTrue(statuses.toString() + "", statuses.containsKey("AliceJoin")) + + bobSession.dataHandler.removeListener(bobEventListener) + + return CryptoTestData(aliceSession, aliceRoomId, bobSession) + } + + /** + * @return Alice, Bob and Sam session + */ + fun doE2ETestWithAliceAndBobAndSamInARoom(): CryptoTestData { + val statuses = HashMap() + + val cryptoTestData = doE2ETestWithAliceAndBobInARoom(true) + val aliceSession = cryptoTestData.firstSession + val aliceRoomId = cryptoTestData.roomId + + val room = aliceSession.dataHandler.getRoom(aliceRoomId) + + val samSession = mTestHelper.createAccount(TestConstants.USER_SAM, defaultSessionParams) + val lock0 = CountDownLatch(1) + + samSession.enableCrypto(true, object : TestApiCallback(lock0) { + override fun onSuccess(info: Void?) { + statuses["enableCrypto"] = "enableCrypto" + super.onSuccess(info) + } + }) + mTestHelper.await(lock0) + + val lock1 = CountDownLatch(2) + + val samEventListener = object : MXEventListener() { + override fun onNewRoom(roomId: String) { + if (TextUtils.equals(roomId, aliceRoomId)) { + if (!statuses.containsKey("onNewRoom")) { + statuses["onNewRoom"] = "onNewRoom" + lock1.countDown() + } + } + } + } + + samSession.dataHandler.addListener(samEventListener) + + room.invite(samSession.myUserId, object : TestApiCallback(lock1) { + override fun onSuccess(info: Void?) { + statuses["invite"] = "invite" + super.onSuccess(info) + } + }) + + mTestHelper.await(lock1) + + Assert.assertTrue(statuses.containsKey("invite") && statuses.containsKey("onNewRoom")) + + samSession.dataHandler.removeListener(samEventListener) + + val lock2 = CountDownLatch(1) + + samSession.joinRoom(aliceRoomId, object : TestApiCallback(lock2) { + override fun onSuccess(info: String) { + statuses["joinRoom"] = "joinRoom" + super.onSuccess(info) + } + }) + + mTestHelper.await(lock2) + Assert.assertTrue(statuses.containsKey("joinRoom")) + + // wait the initial sync + SystemClock.sleep(1000) + + samSession.dataHandler.removeListener(samEventListener) + + return CryptoTestData(aliceSession, aliceRoomId, cryptoTestData.secondSession, samSession) + } + + /** + * @param cryptedBob + * @return Alice and Bob sessions + */ + fun doE2ETestWithAliceAndBobInARoomWithEncryptedMessages(cryptedBob: Boolean): CryptoTestData { + val cryptoTestData = doE2ETestWithAliceAndBobInARoom(cryptedBob) + val aliceSession = cryptoTestData.firstSession + val aliceRoomId = cryptoTestData.roomId + val bobSession = cryptoTestData.secondSession!! + + bobSession.crypto?.setWarnOnUnknownDevices(false) + + aliceSession.crypto?.setWarnOnUnknownDevices(false) + + val roomFromBobPOV = bobSession.dataHandler.getRoom(aliceRoomId) + val roomFromAlicePOV = aliceSession.dataHandler.getRoom(aliceRoomId) + + var messagesReceivedByBobCount = 0 + var lock = CountDownLatch(3) + + val bobEventsListener = object : MXEventListener() { + override fun onLiveEvent(event: Event, roomState: RoomState) { + if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE) && !TextUtils.equals(event.getSender(), bobSession.myUserId)) { + messagesReceivedByBobCount++ + lock.countDown() + } + } + } + + roomFromBobPOV.addEventListener(bobEventsListener) + + val results = HashMap() + + bobSession.dataHandler.addListener(object : MXEventListener() { + override fun onToDeviceEvent(event: Event) { + results["onToDeviceEvent"] = event + lock.countDown() + } + }) + + // Alice sends a message + roomFromAlicePOV.sendEvent(buildTextEvent(messagesFromAlice[0], aliceSession, aliceRoomId), TestApiCallback(lock, true)) + mTestHelper.await(lock) + Assert.assertTrue(results.containsKey("onToDeviceEvent")) + Assert.assertEquals(1, messagesReceivedByBobCount) + + // Bob send a message + lock = CountDownLatch(1) + roomFromBobPOV.sendEvent(buildTextEvent(messagesFromBob[0], bobSession, aliceRoomId), TestApiCallback(lock, true)) + // android does not echo the messages sent from itself + messagesReceivedByBobCount++ + mTestHelper.await(lock) + Assert.assertEquals(2, messagesReceivedByBobCount) + + // Bob send a message + lock = CountDownLatch(1) + roomFromBobPOV.sendEvent(buildTextEvent(messagesFromBob[1], bobSession, aliceRoomId), TestApiCallback(lock, true)) + // android does not echo the messages sent from itself + messagesReceivedByBobCount++ + mTestHelper.await(lock) + Assert.assertEquals(3, messagesReceivedByBobCount) + + // Bob send a message + lock = CountDownLatch(1) + roomFromBobPOV.sendEvent(buildTextEvent(messagesFromBob[2], bobSession, aliceRoomId), TestApiCallback(lock, true)) + // android does not echo the messages sent from itself + messagesReceivedByBobCount++ + mTestHelper.await(lock) + Assert.assertEquals(4, messagesReceivedByBobCount) + + // Alice sends a message + lock = CountDownLatch(2) + roomFromAlicePOV.sendEvent(buildTextEvent(messagesFromAlice[1], aliceSession, aliceRoomId), TestApiCallback(lock, true)) + mTestHelper.await(lock) + Assert.assertEquals(5, messagesReceivedByBobCount) + + return cryptoTestData + } + + fun checkEncryptedEvent(event: Event, roomId: String, clearMessage: String, senderSession: MXSession) { + Assert.assertEquals(Event.EVENT_TYPE_MESSAGE_ENCRYPTED, event.wireType) + Assert.assertNotNull(event.wireContent) + + val eventWireContent = event.wireContent.asJsonObject + Assert.assertNotNull(eventWireContent) + + Assert.assertNull(eventWireContent.get("body")) + Assert.assertEquals(MXCRYPTO_ALGORITHM_MEGOLM, eventWireContent.get("algorithm").asString) + + Assert.assertNotNull(eventWireContent.get("ciphertext")) + Assert.assertNotNull(eventWireContent.get("session_id")) + Assert.assertNotNull(eventWireContent.get("sender_key")) + + Assert.assertEquals(senderSession.credentials.deviceId, eventWireContent.get("device_id").asString) + + Assert.assertNotNull(event.eventId) + Assert.assertEquals(roomId, event.roomId) + Assert.assertEquals(Event.EVENT_TYPE_MESSAGE, event.getType()) + Assert.assertTrue(event.getAge() < 10000) + + val eventContent = event.contentAsJsonObject + Assert.assertNotNull(eventContent) + Assert.assertEquals(clearMessage, eventContent!!.get("body").asString) + Assert.assertEquals(senderSession.myUserId, event.sender) + } +} diff --git a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/TestApiCallback.java b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/TestApiCallback.java deleted file mode 100644 index 50022447e..000000000 --- a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/TestApiCallback.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2018 New Vector Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.androidsdk.common; - -import android.support.annotation.CallSuper; -import android.support.annotation.NonNull; - -import org.matrix.androidsdk.rest.callback.ApiCallback; -import org.matrix.androidsdk.rest.model.MatrixError; -import org.matrix.androidsdk.util.Log; - -import java.util.concurrent.CountDownLatch; - -/** - * Simple implementation of ApiCallback, which count down the CountDownLatch on each API callback - * - * @param - */ -public class TestApiCallback implements ApiCallback { - - @NonNull - private final CountDownLatch mCountDownLatch; - - public TestApiCallback(@NonNull CountDownLatch countDownLatch) { - mCountDownLatch = countDownLatch; - } - - @CallSuper - @Override - public void onSuccess(T info) { - mCountDownLatch.countDown(); - } - - @CallSuper - @Override - public void onNetworkError(Exception e) { - Log.e("TestApiCallback", e.getMessage(), e); - mCountDownLatch.countDown(); - } - - @CallSuper - @Override - public void onMatrixError(MatrixError e) { - Log.e("TestApiCallback", e.getMessage() + " " + e.errcode); - mCountDownLatch.countDown(); - } - - @CallSuper - @Override - public void onUnexpectedError(Exception e) { - Log.e("TestApiCallback", e.getMessage(), e); - mCountDownLatch.countDown(); - } -} diff --git a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/TestApiCallback.kt b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/TestApiCallback.kt new file mode 100644 index 000000000..a561a8dc7 --- /dev/null +++ b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/TestApiCallback.kt @@ -0,0 +1,73 @@ +/* + * Copyright 2018 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.androidsdk.common + +import android.support.annotation.CallSuper +import junit.framework.Assert + +import org.matrix.androidsdk.rest.callback.ApiCallback +import org.matrix.androidsdk.rest.model.MatrixError +import org.matrix.androidsdk.util.Log + +import java.util.concurrent.CountDownLatch + +/** + * Simple implementation of ApiCallback, which count down the CountDownLatch on each API callback + * @param onlySuccessful true to fail if an error occurs. This is the default behavior + * @param + */ +open class TestApiCallback @JvmOverloads constructor(private val countDownLatch: CountDownLatch, + private val onlySuccessful: Boolean = true) : ApiCallback { + + @CallSuper + override fun onSuccess(info: T) { + countDownLatch.countDown() + } + + @CallSuper + override fun onNetworkError(e: Exception) { + Log.e("TestApiCallback", e.message, e) + + if (onlySuccessful) { + Assert.fail("onNetworkError " + e.localizedMessage) + } + + countDownLatch.countDown() + } + + @CallSuper + override fun onMatrixError(e: MatrixError) { + Log.e("TestApiCallback", e.message + " " + e.errcode) + + if (onlySuccessful) { + Assert.fail("onMatrixError " + e.localizedMessage) + } + + countDownLatch.countDown() + } + + @CallSuper + override fun onUnexpectedError(e: Exception) { + Log.e("TestApiCallback", e.message, e) + + if (onlySuccessful) { + Assert.fail("onUnexpectedError " + e.localizedMessage) + } + + countDownLatch.countDown() + } +} diff --git a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/TestConstants.java b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/TestConstants.java index 0a68f2a2a..90e2f38a9 100644 --- a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/TestConstants.java +++ b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/TestConstants.java @@ -16,16 +16,30 @@ package org.matrix.androidsdk.common; +import android.os.Debug; + public class TestConstants { public static final String TESTS_HOME_SERVER_URL = "http://10.0.2.2:8080"; - // Time out to use when waiting for server response - public static final int AWAIT_TIME_OUT_MILLIS = 60_000; + // Time out to use when waiting for server response. 60s + private static final int AWAIT_TIME_OUT_MILLIS = 60_000; + + // Time out to use when waiting for server response, when the debugger is connected. 10 minutes + private static final int AWAIT_TIME_OUT_WITH_DEBUGGER_MILLIS = 10 * 60_000; public static final String USER_ALICE = "Alice"; public static final String USER_BOB = "Bob"; public static final String USER_SAM = "Sam"; public static final String PASSWORD = "password"; + + public static long getTimeOutMillis() { + if (Debug.isDebuggerConnected()) { + // Wait more + return AWAIT_TIME_OUT_WITH_DEBUGGER_MILLIS; + } else { + return AWAIT_TIME_OUT_MILLIS; + } + } } \ No newline at end of file diff --git a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoRestTest.java b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoRestTest.java index f60f5710a..c1a5b546e 100644 --- a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoRestTest.java +++ b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoRestTest.java @@ -62,7 +62,7 @@ public void test01_testDeviceKeys() throws Exception { MXDeviceInfo bobDevice = new MXDeviceInfo("dev1"); bobDevice.userId = bobSession.getMyUserId(); - bobDevice.algorithms = Arrays.asList(MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_OLM); + bobDevice.algorithms = Arrays.asList(CryptoConstantsKt.MXCRYPTO_ALGORITHM_OLM); Map keysMap = new HashMap<>(); keysMap.put("ed25519:" + bobDevice.deviceId, ed25519key); diff --git a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoStoreMigrationTest.kt b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoStoreMigrationTest.kt index bc5457630..daaf960ae 100644 --- a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoStoreMigrationTest.kt +++ b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoStoreMigrationTest.kt @@ -48,6 +48,7 @@ import java.util.concurrent.CountDownLatch class CryptoStoreMigrationTest { private val mTestHelper = CommonTestHelper() + private val mCryptoTestHelper = CryptoTestHelper(mTestHelper) private val cryptoStoreHelper = CryptoStoreHelper() private val sessionTestParamLegacy = SessionTestParams(withInitialSync = true, withCryptoEnabled = true, withLegacyCryptoStore = true) @@ -260,14 +261,14 @@ class CryptoStoreMigrationTest { val context = InstrumentationRegistry.getContext() val results = java.util.HashMap() - val pair = doE2ETestWithAliceAndBobInARoom(true) - val aliceSession = pair.first.first - val aliceRoomId = pair.first.second - val bobSession = pair.second + val cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) + val aliceSession = cryptoTestData.firstSession + val aliceRoomId = cryptoTestData.roomId + val bobSession = cryptoTestData.secondSession val messageFromAlice = "Hello I'm Alice!" - val roomFromBobPOV = bobSession.dataHandler.getRoom(aliceRoomId) + val roomFromBobPOV = bobSession!!.dataHandler.getRoom(aliceRoomId) val roomFromAlicePOV = aliceSession.dataHandler.getRoom(aliceRoomId) Assert.assertTrue(roomFromBobPOV.isEncrypted) @@ -280,7 +281,7 @@ class CryptoStoreMigrationTest { val eventListener = object : MXEventListener() { override fun onLiveEvent(event: Event, roomState: RoomState) { if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) { - checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession) + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession) results["onLiveEvent"] = "onLiveEvent" lock.countDown() @@ -290,7 +291,7 @@ class CryptoStoreMigrationTest { roomFromBobPOV.addEventListener(eventListener) - roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), TestApiCallback(lock)) + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), TestApiCallback(lock)) mTestHelper.await(lock) Assert.assertTrue(results.containsKey("onLiveEvent")) @@ -327,7 +328,7 @@ class CryptoStoreMigrationTest { val eventListener2 = object : EventTimeline.Listener { override fun onEvent(event: Event, direction: EventTimeline.Direction, roomState: RoomState) { if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) { - checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession) + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession) results["onLiveEvent2"] = "onLiveEvent2" lock2.countDown() @@ -342,8 +343,7 @@ class CryptoStoreMigrationTest { mTestHelper.await(lock2) Assert.assertTrue(results.containsKey("onLiveEvent2")) - aliceSession.clear(context) - bobSession.clear(context) + cryptoTestData.clear(context) aliceSession2.clear(context) bobSession2.clear(context) } @@ -383,191 +383,4 @@ class CryptoStoreMigrationTest { companion object { private const val LOG_TAG = "CryptoStoreMigrationTest" } - - /* ========================================================================================== - * TODO REMOVE and replace by call form mCryptoTestHelper (from the branch keys backup) - * ========================================================================================== */ - - /** - * @param cryptedBob - * @return alice and bob sessions - * @throws Exception - */ - @Throws(Exception::class) - private fun doE2ETestWithAliceAndBobInARoom(cryptedBob: Boolean): Pair { - val statuses = java.util.HashMap() - - val sessionAndRoomId = doE2ETestWithAliceInARoom() - val aliceSession = sessionAndRoomId.first - val aliceRoomId = sessionAndRoomId.second - - val room = aliceSession.dataHandler.getRoom(aliceRoomId) - - val bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, sessionTestParamLegacy) - val lock0 = CountDownLatch(1) - - bobSession.enableCrypto(cryptedBob, object : TestApiCallback(lock0) { - override fun onSuccess(info: Void?) { - statuses["enableCrypto"] = "enableCrypto" - super.onSuccess(info) - } - }) - mTestHelper.await(lock0) - - val lock1 = CountDownLatch(2) - - val bobEventListener = object : MXEventListener() { - override fun onNewRoom(roomId: String) { - if (TextUtils.equals(roomId, aliceRoomId)) { - if (!statuses.containsKey("onNewRoom")) { - statuses["onNewRoom"] = "onNewRoom" - lock1.countDown() - } - } - } - } - - bobSession.dataHandler.addListener(bobEventListener) - - room.invite(bobSession.myUserId, object : TestApiCallback(lock1) { - override fun onSuccess(info: Void?) { - statuses["invite"] = "invite" - super.onSuccess(info) - } - }) - - mTestHelper.await(lock1) - - Assert.assertTrue(statuses.containsKey("invite") && statuses.containsKey("onNewRoom")) - - bobSession.dataHandler.removeListener(bobEventListener) - - val lock2 = CountDownLatch(2) - - bobSession.joinRoom(aliceRoomId, object : TestApiCallback(lock2) { - override fun onSuccess(info: String) { - statuses["joinRoom"] = "joinRoom" - super.onSuccess(info) - } - - override fun onNetworkError(e: Exception) { - statuses["onNetworkError"] = e.message!! - super.onNetworkError(e) - } - - override fun onMatrixError(e: MatrixError) { - statuses["onMatrixError"] = e.message - super.onMatrixError(e) - } - - override fun onUnexpectedError(e: Exception) { - statuses["onUnexpectedError"] = e.message!! - super.onUnexpectedError(e) - } - }) - - room.addEventListener(object : MXEventListener() { - override fun onLiveEvent(event: Event, roomState: RoomState) { - if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_STATE_ROOM_MEMBER)) { - val contentToConsider = event.contentAsJsonObject - val member = JsonUtils.toRoomMember(contentToConsider) - - if (TextUtils.equals(member.membership, RoomMember.MEMBERSHIP_JOIN)) { - statuses["AliceJoin"] = "AliceJoin" - lock2.countDown() - } - } - } - }) - - mTestHelper.await(lock2) - Assert.assertTrue(statuses.toString() + "", statuses.containsKey("joinRoom")) - Assert.assertTrue(statuses.toString() + "", statuses.containsKey("AliceJoin")) - - bobSession.dataHandler.removeListener(bobEventListener) - - return Pair(sessionAndRoomId, bobSession) - } - - /** - * @return alice session - * @throws Exception - */ - @Throws(Exception::class) - private fun doE2ETestWithAliceInARoom(): SessionAndRoomId { - val results = java.util.HashMap() - val aliceSession = mTestHelper.createAccount(TestConstants.USER_ALICE, sessionTestParamLegacy) - val lock0 = CountDownLatch(1) - - aliceSession.enableCrypto(true, object : TestApiCallback(lock0) { - override fun onSuccess(info: Void?) { - results["enableCrypto"] = "enableCrypto" - super.onSuccess(info) - } - }) - mTestHelper.await(lock0) - Assert.assertTrue(results.containsKey("enableCrypto")) - - var roomId: String? = null - val lock1 = CountDownLatch(1) - - aliceSession.createRoom(object : TestApiCallback(lock1) { - override fun onSuccess(createdRoomId: String) { - roomId = createdRoomId - super.onSuccess(createdRoomId) - } - }) - - mTestHelper.await(lock1) - Assert.assertNotNull(roomId) - - val room = aliceSession.dataHandler.getRoom(roomId) - - val lock2 = CountDownLatch(1) - room.enableEncryptionWithAlgorithm(MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM, object : TestApiCallback(lock2) { - override fun onSuccess(info: Void?) { - results["enableEncryptionWithAlgorithm"] = "enableEncryptionWithAlgorithm" - super.onSuccess(info) - } - }) - mTestHelper.await(lock2) - Assert.assertTrue(results.containsKey("enableEncryptionWithAlgorithm")) - - return SessionAndRoomId(aliceSession, roomId) - } - - private fun buildTextEvent(text: String, session: MXSession, roomId: String): Event { - val message = Message() - message.msgtype = Message.MSGTYPE_TEXT - message.body = text - - return Event(message, session.credentials.userId, roomId) - } - - private fun checkEncryptedEvent(event: Event, roomId: String, clearMessage: String, senderSession: MXSession) { - Assert.assertEquals(Event.EVENT_TYPE_MESSAGE_ENCRYPTED, event.wireType) - Assert.assertNotNull(event.wireContent) - - val eventWireContent = event.wireContent.asJsonObject - Assert.assertNotNull(eventWireContent) - - Assert.assertNull(eventWireContent.get("body")) - Assert.assertEquals(MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM, eventWireContent.get("algorithm").asString) - - Assert.assertNotNull(eventWireContent.get("ciphertext")) - Assert.assertNotNull(eventWireContent.get("session_id")) - Assert.assertNotNull(eventWireContent.get("sender_key")) - - Assert.assertEquals(senderSession.credentials.deviceId, eventWireContent.get("device_id").asString) - - Assert.assertNotNull(event.eventId) - Assert.assertEquals(roomId, event.roomId) - Assert.assertEquals(Event.EVENT_TYPE_MESSAGE, event.getType()) - Assert.assertTrue(event.getAge() < 10000) - - val eventContent = event.contentAsJsonObject - Assert.assertNotNull(eventContent) - Assert.assertEquals(clearMessage, eventContent!!.get("body").asString) - Assert.assertEquals(senderSession.myUserId, event.sender) - } } \ No newline at end of file diff --git a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoTest.java b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoTest.java index de3eaadf2..cac8e1c71 100644 --- a/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoTest.java +++ b/matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoTest.java @@ -24,7 +24,6 @@ import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import android.text.TextUtils; -import android.util.Pair; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; @@ -38,11 +37,10 @@ import org.matrix.androidsdk.MXDataHandler; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.common.CommonTestHelper; -import org.matrix.androidsdk.common.SessionAndRoomId; -import org.matrix.androidsdk.common.SessionTestParams; +import org.matrix.androidsdk.common.CryptoTestData; +import org.matrix.androidsdk.common.CryptoTestHelper; import org.matrix.androidsdk.common.TestApiCallback; import org.matrix.androidsdk.common.TestConstants; -import org.matrix.androidsdk.common.Triple; import org.matrix.androidsdk.crypto.data.MXDeviceInfo; import org.matrix.androidsdk.crypto.data.MXOlmSessionResult; import org.matrix.androidsdk.crypto.data.MXUsersDevicesMap; @@ -59,7 +57,6 @@ import org.matrix.androidsdk.rest.model.Event; import org.matrix.androidsdk.rest.model.MatrixError; import org.matrix.androidsdk.rest.model.RoomDirectoryVisibility; -import org.matrix.androidsdk.rest.model.RoomMember; import org.matrix.androidsdk.rest.model.login.Credentials; import org.matrix.androidsdk.rest.model.message.Message; import org.matrix.androidsdk.rest.model.message.RelatesTo; @@ -77,29 +74,18 @@ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class CryptoTest { - // Set this value to false to test the new Realm store and to true to test legacy Filestore - private static final boolean USE_LEGACY_CRYPTO_STORE = false; - private CommonTestHelper mTestHelper = new CommonTestHelper(); - - // Lazy loading is on by default now - private static final boolean LAZY_LOADING_ENABLED = true; - - private final SessionTestParams defaultSessionParams = new SessionTestParams(true, false, LAZY_LOADING_ENABLED, USE_LEGACY_CRYPTO_STORE); - private final SessionTestParams encryptedSessionParams = new SessionTestParams(true, true, LAZY_LOADING_ENABLED, USE_LEGACY_CRYPTO_STORE); + private CryptoTestHelper mCryptoTestHelper = new CryptoTestHelper(mTestHelper); private static final String LOG_TAG = "CryptoTest"; - private static final List messagesFromAlice = Arrays.asList("0 - Hello I'm Alice!", "4 - Go!"); - private static final List messagesFromBob = Arrays.asList("1 - Hello I'm Bob!", "2 - Isn't life grand?", "3 - Let's go to the opera."); - @Test public void test01_testCryptoNoDeviceId() throws Exception { Log.e(LOG_TAG, "test01_testCryptoNoDeviceId"); Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams); + MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, mCryptoTestHelper.getDefaultSessionParams()); Assert.assertNull(bobSession.getCrypto()); bobSession.getCredentials().deviceId = null; @@ -127,7 +113,7 @@ public void test02_testCryptoPersistenceInStore() throws Exception { Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams); + MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, mCryptoTestHelper.getDefaultSessionParams()); bobSession.getCredentials().deviceId = "BobDevice"; Assert.assertNull(bobSession.getCrypto()); @@ -162,7 +148,7 @@ public void onSuccess(Void info) { IMXStore store = new MXFileStore(hs, false, context); MXSession bobSession2 = new MXSession.Builder(hs, new MXDataHandler(store, bobCredentials), context) - .withLegacyCryptoStore(USE_LEGACY_CRYPTO_STORE) + .withLegacyCryptoStore(mCryptoTestHelper.USE_LEGACY_CRYPTO_STORE) .build(); final CountDownLatch lock1 = new CountDownLatch(1); @@ -238,7 +224,7 @@ public void test03_testKeysUploadAndDownload() throws Exception { Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - MXSession aliceSession = mTestHelper.createAccount(TestConstants.USER_ALICE, defaultSessionParams); + MXSession aliceSession = mTestHelper.createAccount(TestConstants.USER_ALICE, mCryptoTestHelper.getDefaultSessionParams()); aliceSession.getCredentials().deviceId = "AliceDevice"; CountDownLatch lock0 = new CountDownLatch(1); @@ -252,7 +238,7 @@ public void onSuccess(Void info) { mTestHelper.await(lock0); Assert.assertTrue(results.containsKey("enableCrypto")); - MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams); + MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, mCryptoTestHelper.getDefaultSessionParams()); CountDownLatch lock2 = new CountDownLatch(1); bobSession.getCredentials().deviceId = "BobDevice"; bobSession.enableCrypto(true, new TestApiCallback(lock2) { @@ -290,7 +276,7 @@ public void onSuccess(MXUsersDevicesMap info) { // Continue testing other methods Assert.assertNotNull(bobSession.getCrypto().deviceWithIdentityKey(aliceSession.getCrypto().getOlmDevice().getDeviceCurve25519Key(), - aliceSession.getMyUserId(), MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_OLM)); + aliceSession.getMyUserId(), CryptoConstantsKt.MXCRYPTO_ALGORITHM_OLM)); Assert.assertTrue(aliceDeviceFromBobPOV.isUnknown()); CountDownLatch lock3a = new CountDownLatch(1); @@ -339,7 +325,7 @@ public void onSuccess(Void info) { IMXStore store = new MXFileStore(hs, false, context); MXSession bobSession2 = new MXSession.Builder(hs, new MXDataHandler(store, bobCredentials), context) - .withLegacyCryptoStore(USE_LEGACY_CRYPTO_STORE) + .withLegacyCryptoStore(mCryptoTestHelper.USE_LEGACY_CRYPTO_STORE) .build(); final CountDownLatch lock4 = new CountDownLatch(1); @@ -396,7 +382,7 @@ public void onCryptoSyncComplete() { MXDeviceInfo aliceDeviceFromBobPOV2 = bobSession2.getCrypto() .deviceWithIdentityKey(aliceSession.getCrypto().getOlmDevice().getDeviceCurve25519Key(), - aliceSession.getMyUserId(), MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_OLM); + aliceSession.getMyUserId(), CryptoConstantsKt.MXCRYPTO_ALGORITHM_OLM); Assert.assertNotNull(aliceDeviceFromBobPOV2); Assert.assertEquals(aliceDeviceFromBobPOV2.fingerprint(), aliceSession.getCrypto().getOlmDevice().getDeviceEd25519Key()); @@ -417,7 +403,7 @@ public void onSuccess(MXUsersDevicesMap info) { Assert.assertTrue(results.containsKey("downloadKeys2")); MXDeviceInfo aliceDeviceFromBobPOV3 = bobSession2.getCrypto().deviceWithIdentityKey(aliceSession.getCrypto().getOlmDevice().getDeviceCurve25519Key(), - aliceSession.getMyUserId(), MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_OLM); + aliceSession.getMyUserId(), CryptoConstantsKt.MXCRYPTO_ALGORITHM_OLM); Assert.assertNotNull(aliceDeviceFromBobPOV3); Assert.assertEquals(aliceDeviceFromBobPOV3.fingerprint(), aliceSession.getCrypto().getOlmDevice().getDeviceEd25519Key()); @@ -434,7 +420,7 @@ public void test04_testEnsureOlmSessionsForUsers() throws Exception { Context context = InstrumentationRegistry.getContext(); - MXSession aliceSession = mTestHelper.createAccount(TestConstants.USER_ALICE, defaultSessionParams); + MXSession aliceSession = mTestHelper.createAccount(TestConstants.USER_ALICE, mCryptoTestHelper.getDefaultSessionParams()); final Map results = new HashMap<>(); aliceSession.getCredentials().deviceId = "AliceDevice"; @@ -452,7 +438,7 @@ public void onSuccess(Void info) { mTestHelper.await(lock0); Assert.assertTrue(results.containsKey("enableCryptoAlice")); - MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams); + MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, mCryptoTestHelper.getDefaultSessionParams()); CountDownLatch lock2 = new CountDownLatch(1); bobSession.enableCrypto(true, new TestApiCallback(lock2) { @@ -509,7 +495,7 @@ public void onSuccess(MXUsersDevicesMap info) { IMXStore store = new MXFileStore(hs, false, context); MXSession bobSession2 = new MXSession.Builder(hs, new MXDataHandler(store, bobCredentials), context) - .withLegacyCryptoStore(USE_LEGACY_CRYPTO_STORE) + .withLegacyCryptoStore(mCryptoTestHelper.USE_LEGACY_CRYPTO_STORE) .build(); final CountDownLatch lock5 = new CountDownLatch(1); @@ -600,7 +586,7 @@ public void test05_testRoomIsEncrypted() throws Exception { Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams); + MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, mCryptoTestHelper.getDefaultSessionParams()); CountDownLatch lock0 = new CountDownLatch(1); bobSession.enableCrypto(true, new TestApiCallback(lock0) { @@ -645,7 +631,7 @@ public void onLiveEvent(Event event, RoomState roomState) { }); CountDownLatch lock2 = new CountDownLatch(1); - room.enableEncryptionWithAlgorithm(MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM, new TestApiCallback(lock2) { + room.enableEncryptionWithAlgorithm(CryptoConstantsKt.MXCRYPTO_ALGORITHM_MEGOLM, new TestApiCallback(lock2) { @Override public void onSuccess(Void info) { results.put("enableEncryptionWithAlgorithm", "enableEncryptionWithAlgorithm"); @@ -662,7 +648,7 @@ public void onSuccess(Void info) { Thread.sleep(1000); // Check algo in store - Assert.assertEquals(MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM, bobSession.getCrypto().getCryptoStore().getRoomAlgorithm(room.getRoomId())); + Assert.assertEquals(CryptoConstantsKt.MXCRYPTO_ALGORITHM_MEGOLM, bobSession.getCrypto().getCryptoStore().getRoomAlgorithm(room.getRoomId())); bobSession.clear(context); } @@ -673,9 +659,9 @@ public void test06_testAliceInAEncryptedRoom() throws Exception { Context context = InstrumentationRegistry.getContext(); - SessionAndRoomId sessionAndRoomId = doE2ETestWithAliceInARoom(); - MXSession aliceSession = sessionAndRoomId.first; - String aliceRoomId = sessionAndRoomId.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceInARoom(); + MXSession aliceSession = cryptoTestData.getFirstSession(); + String aliceRoomId = cryptoTestData.getRoomId(); final String message = "Hello myself!"; @@ -688,11 +674,11 @@ public void test06_testAliceInAEncryptedRoom() throws Exception { // the IOS client echoes the message // the android client does not - roomFromAlicePOV.sendEvent(buildTextEvent(message, aliceSession, aliceRoomId), new TestApiCallback(lock1)); + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(message, aliceSession, aliceRoomId), new TestApiCallback(lock1)); mTestHelper.await(lock1); - aliceSession.clear(context); + cryptoTestData.clear(context); } @Test @@ -702,10 +688,10 @@ public void test07_testAliceAndBobInAEncryptedRoom() throws Exception { Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Pair pair = doE2ETestWithAliceAndBobInARoom(true); - final MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - final MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); final String messageFromAlice = "Hello I'm Alice!"; @@ -717,7 +703,7 @@ public void test07_testAliceAndBobInAEncryptedRoom() throws Exception { CountDownLatch lock1 = new CountDownLatch(1); - roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new TestApiCallback(lock1) { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new TestApiCallback(lock1, false) { @Override public void onMatrixError(MatrixError e) { results.put("sendEventError", e); @@ -752,7 +738,7 @@ public void onSuccess(Void info) { @Override public void onLiveEvent(Event event, RoomState roomState) { if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) { - checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); results.put("onLiveEvent", "onLiveEvent"); lock3.countDown(); @@ -770,7 +756,7 @@ public void onToDeviceEvent(Event event) { roomFromBobPOV.addEventListener(eventListener); - roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new TestApiCallback(lock3)); + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new TestApiCallback(lock3)); mTestHelper.await(lock3); Assert.assertTrue(results.containsKey("onToDeviceEvent")); @@ -782,17 +768,18 @@ public void onToDeviceEvent(Event event) { Assert.assertEquals(MXDeviceList.TRACKING_STATUS_UP_TO_DATE, aliceSession.getCrypto().getDeviceTrackingStatus(bobSession.getMyUserId())); Assert.assertEquals(MXDeviceList.TRACKING_STATUS_UP_TO_DATE, aliceSession.getCrypto().getDeviceTrackingStatus(aliceSession.getMyUserId())); - bobSession.clear(context); + cryptoTestData.clear(context); } @Test public void test08_testAliceAndBobInAEncryptedRoom2() throws Exception { Log.e(LOG_TAG, "test08_testAliceAndBobInAEncryptedRoom2"); + Context context = InstrumentationRegistry.getContext(); - Pair pair = doE2ETestWithAliceAndBobInARoom(true); - final MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - final MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); bobSession.getCrypto().setWarnOnUnknownDevices(false); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -812,7 +799,7 @@ public void test08_testAliceAndBobInAEncryptedRoom2() throws Exception { @Override public void onLiveEvent(Event event, RoomState roomState) { if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE) && !TextUtils.equals(event.getSender(), bobSession.getMyUserId())) { - checkEncryptedEvent(event, aliceRoomId, messagesFromAlice.get(nbReceivedMessagesFromAlice[0]), aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, mCryptoTestHelper.getMessagesFromAlice().get(nbReceivedMessagesFromAlice[0]), aliceSession); nbReceivedMessagesFromAlice[0]++; list.get(list.size() - 1).countDown(); @@ -824,7 +811,7 @@ public void onLiveEvent(Event event, RoomState roomState) { @Override public void onLiveEvent(Event event, RoomState roomState) { if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE) && !TextUtils.equals(event.getSender(), aliceSession.getMyUserId())) { - checkEncryptedEvent(event, aliceRoomId, messagesFromBob.get(nbReceivedMessagesFromBob[0]), bobSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, mCryptoTestHelper.getMessagesFromBob().get(nbReceivedMessagesFromBob[0]), bobSession); nbReceivedMessagesFromBob[0]++; list.get(list.size() - 1).countDown(); @@ -853,30 +840,32 @@ public void onToDeviceEvent(Event event) { } }); - roomFromAlicePOV.sendEvent(buildTextEvent(messagesFromAlice.get(nbReceivedMessagesFromAlice[0]), aliceSession, aliceRoomId), callback); + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(mCryptoTestHelper.getMessagesFromAlice().get(nbReceivedMessagesFromAlice[0]), aliceSession, aliceRoomId), callback); mTestHelper.await(list.get(list.size() - 1)); Assert.assertTrue(results.containsKey("onToDeviceEvent")); Assert.assertEquals(1, nbReceivedMessagesFromAlice[0]); list.add(new CountDownLatch(1)); - roomFromBobPOV.sendEvent(buildTextEvent(messagesFromBob.get(nbReceivedMessagesFromBob[0]), bobSession, aliceRoomId), callback); + roomFromBobPOV.sendEvent(mCryptoTestHelper.buildTextEvent(mCryptoTestHelper.getMessagesFromBob().get(nbReceivedMessagesFromBob[0]), bobSession, aliceRoomId), callback); mTestHelper.await(list.get(list.size() - 1)); Assert.assertEquals(1, nbReceivedMessagesFromBob[0]); list.add(new CountDownLatch(1)); - roomFromBobPOV.sendEvent(buildTextEvent(messagesFromBob.get(nbReceivedMessagesFromBob[0]), bobSession, aliceRoomId), callback); + roomFromBobPOV.sendEvent(mCryptoTestHelper.buildTextEvent(mCryptoTestHelper.getMessagesFromBob().get(nbReceivedMessagesFromBob[0]), bobSession, aliceRoomId), callback); mTestHelper.await(list.get(list.size() - 1)); Assert.assertEquals(2, nbReceivedMessagesFromBob[0]); list.add(new CountDownLatch(1)); - roomFromBobPOV.sendEvent(buildTextEvent(messagesFromBob.get(nbReceivedMessagesFromBob[0]), bobSession, aliceRoomId), callback); + roomFromBobPOV.sendEvent(mCryptoTestHelper.buildTextEvent(mCryptoTestHelper.getMessagesFromBob().get(nbReceivedMessagesFromBob[0]), bobSession, aliceRoomId), callback); mTestHelper.await(list.get(list.size() - 1)); Assert.assertEquals(3, nbReceivedMessagesFromBob[0]); list.add(new CountDownLatch(1)); - roomFromAlicePOV.sendEvent(buildTextEvent(messagesFromAlice.get(nbReceivedMessagesFromAlice[0]), aliceSession, aliceRoomId), callback); + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(mCryptoTestHelper.getMessagesFromAlice().get(nbReceivedMessagesFromAlice[0]), aliceSession, aliceRoomId), callback); mTestHelper.await(list.get(list.size() - 1)); Assert.assertEquals(2, nbReceivedMessagesFromAlice[0]); + + cryptoTestData.clear(context); } @Test @@ -886,9 +875,9 @@ public void test09_testAliceInAEncryptedRoomAfterInitialSync() throws Exception Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - SessionAndRoomId sessionAndRoomId = doE2ETestWithAliceInARoom(); - MXSession aliceSession = sessionAndRoomId.first; - final String aliceRoomId = sessionAndRoomId.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceInARoom(); + MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -905,7 +894,7 @@ public void test09_testAliceInAEncryptedRoomAfterInitialSync() throws Exception final CountDownLatch lock1 = new CountDownLatch(1); final MXSession aliceSession2 = new MXSession.Builder(hs, new MXDataHandler(store, aliceCredentials), context) - .withLegacyCryptoStore(USE_LEGACY_CRYPTO_STORE) + .withLegacyCryptoStore(mCryptoTestHelper.USE_LEGACY_CRYPTO_STORE) .build(); MXStoreListener listener = new MXStoreListener() { @@ -968,7 +957,7 @@ public void onCryptoSyncComplete() { @Override public void onLiveEvent(Event event, RoomState roomState) { if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) { - checkEncryptedEvent(event, aliceRoomId, message, aliceSession2); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, message, aliceSession2); lock2.countDown(); } @@ -980,7 +969,7 @@ public void onLiveEvent(Event event, RoomState roomState) { // the IOS client echoes the message // the android client does not - roomFromAlicePOV2.sendEvent(buildTextEvent(message, aliceSession2, aliceRoomId), new TestApiCallback(lock2) { + roomFromAlicePOV2.sendEvent(mCryptoTestHelper.buildTextEvent(message, aliceSession2, aliceRoomId), new TestApiCallback(lock2) { @Override public void onSuccess(Void info) { results.put("sendEvent", "sendEvent"); @@ -991,6 +980,7 @@ public void onSuccess(Void info) { mTestHelper.await(lock2); Assert.assertTrue(results.containsKey("sendEvent")); + cryptoTestData.clear(context); aliceSession2.clear(context); } @@ -1001,9 +991,9 @@ public void test10_testAliceDecryptOldMessageWithANewDeviceInAEncryptedRoom() th Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - SessionAndRoomId sessionAndRoomId = doE2ETestWithAliceInARoom(); - MXSession aliceSession = sessionAndRoomId.first; - String aliceRoomId = sessionAndRoomId.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceInARoom(); + MXSession aliceSession = cryptoTestData.getFirstSession(); + String aliceRoomId = cryptoTestData.getRoomId(); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -1012,7 +1002,7 @@ public void test10_testAliceDecryptOldMessageWithANewDeviceInAEncryptedRoom() th Room roomFromAlicePOV = aliceSession.getDataHandler().getRoom(aliceRoomId); CountDownLatch lock1 = new CountDownLatch(1); - roomFromAlicePOV.sendEvent(buildTextEvent(message, aliceSession, aliceRoomId), new TestApiCallback(lock1) { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(message, aliceSession, aliceRoomId), new TestApiCallback(lock1) { @Override public void onSuccess(Void info) { results.put("sendEvent", "sendEvent"); @@ -1039,7 +1029,7 @@ public void onSuccess(Void info) { IMXStore store = new MXFileStore(hs, false, context); MXSession aliceSession2 = new MXSession.Builder(hs, new MXDataHandler(store, aliceCredentials2), context) - .withLegacyCryptoStore(USE_LEGACY_CRYPTO_STORE) + .withLegacyCryptoStore(mCryptoTestHelper.USE_LEGACY_CRYPTO_STORE) .build(); aliceSession2.enableCryptoWhenStarting(); @@ -1106,6 +1096,8 @@ public void onCryptoSyncComplete() { Assert.assertNull(event.getClearEvent()); Assert.assertNotNull(event.getCryptoError()); Assert.assertEquals(MXCryptoError.UNKNOWN_INBOUND_SESSION_ID_ERROR_CODE, event.getCryptoError().errcode); + + cryptoTestData.clear(context); aliceSession2.clear(context); } @@ -1116,10 +1108,10 @@ public void test11_testAliceAndBobInAEncryptedRoomBackPaginationFromMemoryStore( Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Pair pair = doE2ETestWithAliceAndBobInARoomWithEncryptedMessages(true); - MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages(true); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); Credentials bobCredentials = bobSession.getCredentials(); bobSession.clear(context); @@ -1131,7 +1123,7 @@ public void test11_testAliceAndBobInAEncryptedRoomBackPaginationFromMemoryStore( final CountDownLatch lock1 = new CountDownLatch(2); MXSession bobSession2 = new MXSession.Builder(hs, new MXDataHandler(store, bobCredentials), context) - .withLegacyCryptoStore(USE_LEGACY_CRYPTO_STORE) + .withLegacyCryptoStore(mCryptoTestHelper.USE_LEGACY_CRYPTO_STORE) .build(); MXEventListener eventListener = new MXEventListener() { @@ -1187,18 +1179,18 @@ public void onSuccess(Integer info) { Assert.assertTrue(results.containsKey("backPaginate")); Assert.assertEquals(receivedEvents.size() + " instead of 5", 5, receivedEvents.size()); - checkEncryptedEvent(receivedEvents.get(0), aliceRoomId, messagesFromAlice.get(1), aliceSession); + mCryptoTestHelper.checkEncryptedEvent(receivedEvents.get(0), aliceRoomId, mCryptoTestHelper.getMessagesFromAlice().get(1), aliceSession); - checkEncryptedEvent(receivedEvents.get(1), aliceRoomId, messagesFromBob.get(2), bobSession); + mCryptoTestHelper.checkEncryptedEvent(receivedEvents.get(1), aliceRoomId, mCryptoTestHelper.getMessagesFromBob().get(2), bobSession); - checkEncryptedEvent(receivedEvents.get(2), aliceRoomId, messagesFromBob.get(1), bobSession); + mCryptoTestHelper.checkEncryptedEvent(receivedEvents.get(2), aliceRoomId, mCryptoTestHelper.getMessagesFromBob().get(1), bobSession); - checkEncryptedEvent(receivedEvents.get(3), aliceRoomId, messagesFromBob.get(0), bobSession); + mCryptoTestHelper.checkEncryptedEvent(receivedEvents.get(3), aliceRoomId, mCryptoTestHelper.getMessagesFromBob().get(0), bobSession); - checkEncryptedEvent(receivedEvents.get(4), aliceRoomId, messagesFromAlice.get(0), aliceSession); + mCryptoTestHelper.checkEncryptedEvent(receivedEvents.get(4), aliceRoomId, mCryptoTestHelper.getMessagesFromAlice().get(0), aliceSession); + cryptoTestData.clear(context); bobSession2.clear(context); - aliceSession.clear(context); } @Test @@ -1208,10 +1200,10 @@ public void test12_testAliceAndBobInAEncryptedRoomBackPaginationFromHomeServer() Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Pair pair = doE2ETestWithAliceAndBobInARoomWithEncryptedMessages(true); - MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages(true); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); String eventId = bobSession.getDataHandler().getStore().getLatestEvent(aliceRoomId).eventId; @@ -1242,30 +1234,30 @@ public void onSuccess(Integer info) { Assert.assertTrue(results.containsKey("backPaginate")); Assert.assertEquals(5, receivedEvents.size()); - checkEncryptedEvent(receivedEvents.get(0), aliceRoomId, messagesFromAlice.get(1), aliceSession); + mCryptoTestHelper.checkEncryptedEvent(receivedEvents.get(0), aliceRoomId, mCryptoTestHelper.getMessagesFromAlice().get(1), aliceSession); - checkEncryptedEvent(receivedEvents.get(1), aliceRoomId, messagesFromBob.get(2), bobSession); + mCryptoTestHelper.checkEncryptedEvent(receivedEvents.get(1), aliceRoomId, mCryptoTestHelper.getMessagesFromBob().get(2), bobSession); - checkEncryptedEvent(receivedEvents.get(2), aliceRoomId, messagesFromBob.get(1), bobSession); + mCryptoTestHelper.checkEncryptedEvent(receivedEvents.get(2), aliceRoomId, mCryptoTestHelper.getMessagesFromBob().get(1), bobSession); - checkEncryptedEvent(receivedEvents.get(3), aliceRoomId, messagesFromBob.get(0), bobSession); + mCryptoTestHelper.checkEncryptedEvent(receivedEvents.get(3), aliceRoomId, mCryptoTestHelper.getMessagesFromBob().get(0), bobSession); - checkEncryptedEvent(receivedEvents.get(4), aliceRoomId, messagesFromAlice.get(0), aliceSession); + mCryptoTestHelper.checkEncryptedEvent(receivedEvents.get(4), aliceRoomId, mCryptoTestHelper.getMessagesFromAlice().get(0), aliceSession); - bobSession.clear(context); - aliceSession.clear(context); + cryptoTestData.clear(context); } @Test public void test13_testAliceAndNotEncryptedBobInACryptedRoom() throws Exception { Log.e(LOG_TAG, "test13_testAliceAndNotEncryptedBobInACryptedRoom"); + Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Pair pair = doE2ETestWithAliceAndBobInARoom(false); - final MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - final MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(false); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -1291,7 +1283,7 @@ public void onLiveEvent(Event event, RoomState roomState) { roomFromBobPOV.addEventListener(bobEventListener); - roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new SimpleApiCallback() { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // Ignore @@ -1324,7 +1316,7 @@ public void onLiveEvent(Event event, RoomState roomState) { roomFromAlicePOV.addEventListener(aliceEventListener); - roomFromBobPOV.sendEvent(buildTextEvent("Hello I'm Bob!", bobSession, aliceRoomId), new SimpleApiCallback() { + roomFromBobPOV.sendEvent(mCryptoTestHelper.buildTextEvent("Hello I'm Bob!", bobSession, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // ignore @@ -1336,6 +1328,8 @@ public void onSuccess(Void info) { event = (Event) results.get("aliceEcho"); Assert.assertFalse(event.isEncrypted()); + + cryptoTestData.clear(context); } @Test @@ -1345,11 +1339,11 @@ public void test14_testCryptoDeviceBlockAndLeave() throws Exception { Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Triple triple = doE2ETestWithAliceAndBobAndSamInARoom(); - MXSession aliceSession = triple.first.first; - final String aliceRoomId = triple.first.second; - MXSession bobSession = triple.second; - MXSession samSession = triple.third; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobAndSamInARoom(); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); + final MXSession samSession = cryptoTestData.getThirdSession(); bobSession.getCrypto().setWarnOnUnknownDevices(false); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -1387,7 +1381,7 @@ public void onLiveEvent(Event event, RoomState roomState) { roomFromSamPOV.addEventListener(samEventsListener0); // even if the device blocked, the message must be decrypted until there is a session id rolling - roomFromBobPOV.sendEvent(buildTextEvent("msg1", bobSession, aliceRoomId), new TestApiCallback(lock0) { + roomFromBobPOV.sendEvent(mCryptoTestHelper.buildTextEvent("msg1", bobSession, aliceRoomId), new TestApiCallback(lock0) { @Override public void onSuccess(Void info) { results.put("send0", "send0"); @@ -1426,7 +1420,7 @@ public void onLiveEvent(Event event, RoomState roomState) { }; roomFromSamPOV.addEventListener(samEventsListener1); - roomFromAlicePOV.sendEvent(buildTextEvent("msg1", aliceSession, aliceRoomId), new TestApiCallback(lock1) { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent("msg1", aliceSession, aliceRoomId), new TestApiCallback(lock1) { @Override public void onSuccess(Void info) { results.put("send1", "send1"); @@ -1477,7 +1471,7 @@ public void onLiveEvent(Event event, RoomState roomState) { roomFromSamPOV.addEventListener(samEventsListener2); // even if the device blocked, the message must be decrypted until there is a session id rolling - roomFromBobPOV.sendEvent(buildTextEvent("msg2", bobSession, aliceRoomId), new TestApiCallback(lock2) { + roomFromBobPOV.sendEvent(mCryptoTestHelper.buildTextEvent("msg2", bobSession, aliceRoomId), new TestApiCallback(lock2) { @Override public void onSuccess(Void info) { results.put("send2", "send2"); @@ -1526,7 +1520,7 @@ public void onLiveEvent(Event event, RoomState roomState) { roomFromAlicePOV.addEventListener(aliceEventsListener3); // even if the device blocked, the message must be decrypted until there is a session id rolling - roomFromBobPOV.sendEvent(buildTextEvent("msg3", bobSession, aliceRoomId), new TestApiCallback(lock4) { + roomFromBobPOV.sendEvent(mCryptoTestHelper.buildTextEvent("msg3", bobSession, aliceRoomId), new TestApiCallback(lock4) { @Override public void onSuccess(Void info) { results.put("send3", "send3"); @@ -1537,20 +1531,19 @@ public void onSuccess(Void info) { mTestHelper.await(lock4); Assert.assertTrue(results.containsKey("send3") && results.containsKey("alice3")); - bobSession.clear(context); - aliceSession.clear(context); - samSession.clear(context); + cryptoTestData.clear(context); } @Test public void test15_testReplayAttack() throws Exception { Log.e(LOG_TAG, "test15_testReplayAttack"); + Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Pair pair = doE2ETestWithAliceAndBobInARoom(true); - MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - final MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); bobSession.getCrypto().setWarnOnUnknownDevices(false); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -1590,7 +1583,7 @@ public void onToDeviceEvent(Event event) { } }); - roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new SimpleApiCallback() { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // Ignore @@ -1609,19 +1602,22 @@ public void onSuccess(Void info) { // Decrypting it with no replay attack mitigation must still work bobSession.getDataHandler().decryptEvent(decryptedEvent, null); - checkEncryptedEvent(decryptedEvent, aliceRoomId, messageFromAlice, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(decryptedEvent, aliceRoomId, messageFromAlice, aliceSession); + + cryptoTestData.clear(context); } @Test public void test16_testRoomKeyReshare() throws Exception { Log.e(LOG_TAG, "test16_testRoomKeyReshare"); + Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Pair pair = doE2ETestWithAliceAndBobInARoom(true); - MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); bobSession.getCrypto().setWarnOnUnknownDevices(false); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -1660,7 +1656,7 @@ public void onEvent(Event event, EventTimeline.Direction direction, RoomState ro roomFromBobPOV.getTimeline().addEventTimelineListener(eventTimelineListener); - roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new SimpleApiCallback() { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // Ignore @@ -1672,7 +1668,7 @@ public void onSuccess(Void info) { Assert.assertEquals(1, receivedEvents.size()); Event event = receivedEvents.get(0); - checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); // Reinject a modified version of the received room_key event from Alice. // From Bob pov, that mimics Alice resharing her keys but with an advanced outbound group session. @@ -1691,19 +1687,22 @@ public void onSuccess(Void info) { event.setClearData(null); bobSession.getDataHandler().decryptEvent(event, null); - checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); + + cryptoTestData.clear(context); } @Test public void test17_testLateRoomKey() throws Exception { Log.e(LOG_TAG, "test17_testLateRoomKey"); + Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Pair pair = doE2ETestWithAliceAndBobInARoom(true); - MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); bobSession.getCrypto().setWarnOnUnknownDevices(false); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -1741,7 +1740,7 @@ public void onEvent(Event event, EventTimeline.Direction direction, RoomState ro roomFromBobPOV.getTimeline().addEventTimelineListener(eventTimelineListener); - roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new SimpleApiCallback() { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // Ignore @@ -1753,7 +1752,7 @@ public void onSuccess(Void info) { Assert.assertEquals(1, receivedEvents.size()); Event event = receivedEvents.get(0); - checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); // Reinject a modified version of the received room_key event from Alice. // From Bob pov, that mimics Alice resharing her keys but with an advanced outbound group session. @@ -1793,8 +1792,10 @@ public void onEventDecrypted(Event event) { Assert.assertTrue(results.containsKey("onEventDecrypted")); Assert.assertEquals(1, receivedEvents.size()); - checkEncryptedEvent(receivedEvents.get(0), aliceRoomId, messageFromAlice, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(receivedEvents.get(0), aliceRoomId, messageFromAlice, aliceSession); Assert.assertNull(receivedEvents.get(0).getCryptoError()); + + cryptoTestData.clear(context); } @Test @@ -1803,10 +1804,10 @@ public void test18_testAliceAndBobWithNewDevice() throws Exception { Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Pair pair = doE2ETestWithAliceAndBobInARoom(true); - MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); bobSession.getCrypto().setWarnOnUnknownDevices(false); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -1846,7 +1847,7 @@ public void onEvent(Event event, EventTimeline.Direction direction, RoomState ro String aliceMessage1 = "Hello I'm Alice!"; - roomFromAlicePOV.sendEvent(buildTextEvent(aliceMessage1, aliceSession, aliceRoomId), new SimpleApiCallback() { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(aliceMessage1, aliceSession, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // Ignore @@ -1858,7 +1859,7 @@ public void onSuccess(Void info) { Assert.assertEquals(1, receivedEvents.size()); Event event = receivedEvents.get(0); - checkEncryptedEvent(event, aliceRoomId, aliceMessage1, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, aliceMessage1, aliceSession); // logout CountDownLatch lock2 = new CountDownLatch(1); @@ -1887,7 +1888,7 @@ public void onToDeviceEvent(Event event) { aliceSession.getDataHandler().addListener(aliceEventListener); // login with a new device id - MXSession bobSession2 = mTestHelper.logIntoAccount(bobSession.getMyUserId(), encryptedSessionParams); + MXSession bobSession2 = mTestHelper.logIntoAccount(bobSession.getMyUserId(), mCryptoTestHelper.getEncryptedSessionParams()); String bobDeviceId2 = bobSession2.getCredentials().deviceId; Assert.assertNotEquals(bobDeviceId2, bobDeviceId1); @@ -1919,7 +1920,7 @@ public void onEvent(Event event, EventTimeline.Direction direction, RoomState ro roomFromBobPOV2.getTimeline().addEventTimelineListener(eventTimelineListener4); String aliceMessage2 = "Hello I'm still Alice!"; - roomFromAlicePOV.sendEvent(buildTextEvent(aliceMessage2, aliceSession, aliceRoomId), new SimpleApiCallback() { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(aliceMessage2, aliceSession, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // Ignore @@ -1930,7 +1931,9 @@ public void onSuccess(Void info) { Assert.assertEquals("received event of type " + results.get("event4"), 1, receivedEvents4.size()); event = receivedEvents4.get(0); - checkEncryptedEvent(event, aliceRoomId, aliceMessage2, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, aliceMessage2, aliceSession); + + cryptoTestData.clear(context); } @Test @@ -1939,10 +1942,10 @@ public void test19_testAliceWithNewDeviceAndBobWithNewDevice() throws Exception Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Pair pair = doE2ETestWithAliceAndBobInARoom(true); - MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); bobSession.getCrypto().setWarnOnUnknownDevices(false); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -1983,7 +1986,7 @@ public void onEvent(Event event, EventTimeline.Direction direction, RoomState ro String aliceMessage1 = "Hello I'm Alice!"; - roomFromAlicePOV.sendEvent(buildTextEvent(aliceMessage1, aliceSession, aliceRoomId), new SimpleApiCallback() { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(aliceMessage1, aliceSession, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // Ignore @@ -1995,7 +1998,7 @@ public void onSuccess(Void info) { Assert.assertEquals(1, receivedEvents.size()); Event event = receivedEvents.get(0); - checkEncryptedEvent(event, aliceRoomId, aliceMessage1, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, aliceMessage1, aliceSession); // logout CountDownLatch lock2 = new CountDownLatch(1); @@ -2020,11 +2023,11 @@ public void onSuccess(Void info) { mTestHelper.await(lock3); Assert.assertTrue(results.containsKey("alicelogout")); - MXSession bobSession2 = mTestHelper.logIntoAccount(bobSession.getMyUserId(), encryptedSessionParams); + MXSession bobSession2 = mTestHelper.logIntoAccount(bobSession.getMyUserId(), mCryptoTestHelper.getEncryptedSessionParams()); Assert.assertNotNull(bobSession2); bobSession2.getCrypto().setWarnOnUnknownDevices(false); - MXSession aliceSession2 = mTestHelper.logIntoAccount(aliceSession.getMyUserId(), encryptedSessionParams); + MXSession aliceSession2 = mTestHelper.logIntoAccount(aliceSession.getMyUserId(), mCryptoTestHelper.getEncryptedSessionParams()); Assert.assertNotNull(aliceSession2); aliceSession2.getCrypto().setWarnOnUnknownDevices(false); @@ -2052,7 +2055,7 @@ public void onEvent(Event event, EventTimeline.Direction direction, RoomState ro roomFromBob2POV.getTimeline().addEventTimelineListener(eventTimelineListener2); String messageFromAlice2 = "Hello I'm still Alice!"; - roomFromAlice2POV.sendEvent(buildTextEvent(messageFromAlice2, aliceSession2, aliceRoomId), new SimpleApiCallback() { + roomFromAlice2POV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice2, aliceSession2, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // Ignore @@ -2063,18 +2066,22 @@ public void onSuccess(Void info) { Assert.assertEquals(1, receivedEvents2.size()); event = receivedEvents2.get(0); - checkEncryptedEvent(event, aliceRoomId, messageFromAlice2, aliceSession2); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, messageFromAlice2, aliceSession2); + + cryptoTestData.clear(context); + aliceSession2.clear(context); } @Test public void test20_testAliceAndBlockedBob() throws Exception { Log.e(LOG_TAG, "test20_testAliceAndBlockedBob"); + Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Pair pair = doE2ETestWithAliceAndBobInARoom(true); - MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); bobSession.getCrypto().setWarnOnUnknownDevices(false); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -2101,7 +2108,7 @@ public void onEvent(Event event, EventTimeline.Direction direction, RoomState ro String aliceMessage1 = "Hello I'm Alice!"; - roomFromAlicePOV.sendEvent(buildTextEvent(aliceMessage1, aliceSession, aliceRoomId), new SimpleApiCallback() { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(aliceMessage1, aliceSession, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // Ignore @@ -2112,7 +2119,7 @@ public void onSuccess(Void info) { Assert.assertEquals(1, receivedEvents.size()); Event event = receivedEvents.get(0); - checkEncryptedEvent(event, aliceRoomId, aliceMessage1, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, aliceMessage1, aliceSession); // block the bob's device CountDownLatch lock1b = new CountDownLatch(1); @@ -2145,7 +2152,7 @@ public void onEvent(Event event, EventTimeline.Direction direction, RoomState ro String aliceMessage2 = "Hello I'm still Alice!"; - roomFromAlicePOV.sendEvent(buildTextEvent(aliceMessage2, aliceSession, aliceRoomId), new SimpleApiCallback() { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(aliceMessage2, aliceSession, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // Ignore @@ -2190,7 +2197,7 @@ public void onEvent(Event event, EventTimeline.Direction direction, RoomState ro String aliceMessage3 = "Hello I'm still Alice and you can read this!"; - roomFromAlicePOV.sendEvent(buildTextEvent(aliceMessage3, aliceSession, aliceRoomId), new SimpleApiCallback() { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(aliceMessage3, aliceSession, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // Ignore @@ -2201,19 +2208,22 @@ public void onSuccess(Void info) { Assert.assertEquals(1, receivedEvents3.size()); event = receivedEvents3.get(0); - checkEncryptedEvent(event, aliceRoomId, aliceMessage3, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, aliceMessage3, aliceSession); + + cryptoTestData.clear(context); } @Test public void test21_testDownloadKeysWithUnreachableHS() throws Exception { Log.e(LOG_TAG, "test21_testDownloadKeysWithUnreachableHS"); + Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Pair pair = doE2ETestWithAliceAndBobInARoom(true); - MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); bobSession.getCrypto().setWarnOnUnknownDevices(false); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -2249,17 +2259,20 @@ public void onSuccess(MXUsersDevicesMap info) { List bobDevices = usersDevicesInfoMap.getUserDeviceIds(bobSession.getMyUserId()); Assert.assertNotNull(bobDevices); + + cryptoTestData.clear(context); } @Test public void test22_testDownloadKeysForUserWithNoDevice() throws Exception { Log.e(LOG_TAG, "test22_testDownloadKeysForUserWithNoDevice"); + Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Pair pair = doE2ETestWithAliceAndBobInARoom(false); - MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(false); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -2297,6 +2310,8 @@ public void onSuccess(MXUsersDevicesMap info) { mTestHelper.await(lock2); Assert.assertTrue(results.containsKey("downloadKeys2")); + + cryptoTestData.clear(context); } @Test @@ -2306,10 +2321,10 @@ public void test23_testFirstMessageSentWhileSessionWasPaused() throws Exception final String messageFromAlice = "Hello I'm Alice!"; final Map results = new HashMap<>(); - Pair pair = doE2ETestWithAliceAndBobInARoom(true); - final MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); bobSession.getCrypto().setWarnOnUnknownDevices(false); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -2327,7 +2342,7 @@ public void test23_testFirstMessageSentWhileSessionWasPaused() throws Exception CountDownLatch lock0 = new CountDownLatch(1); - roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new TestApiCallback(lock0) { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new TestApiCallback(lock0) { @Override public void onSuccess(Void info) { results.put("sendEvent", "sendEvent"); @@ -2343,7 +2358,7 @@ public void onSuccess(Void info) { @Override public void onLiveEvent(Event event, RoomState roomState) { if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) { - checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); results.put("onLiveEvent", "onLiveEvent"); lock2.countDown(); @@ -2367,8 +2382,7 @@ public void onToDeviceEvent(Event event) { Assert.assertTrue(results.containsKey("onToDeviceEvent")); Assert.assertTrue(results.containsKey("onLiveEvent")); - bobSession.clear(context); - aliceSession.clear(context); + cryptoTestData.clear(context); } @Test @@ -2377,9 +2391,9 @@ public void test24_testExportImport() throws Exception { Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - SessionAndRoomId sessionAndRoomId = doE2ETestWithAliceInARoom(); - MXSession aliceSession = sessionAndRoomId.first; - String aliceRoomId = sessionAndRoomId.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceInARoom(); + MXSession aliceSession = cryptoTestData.getFirstSession(); + String aliceRoomId = cryptoTestData.getRoomId(); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -2389,7 +2403,7 @@ public void test24_testExportImport() throws Exception { Room roomFromAlicePOV = aliceSession.getDataHandler().getRoom(aliceRoomId); CountDownLatch lock1 = new CountDownLatch(1); - roomFromAlicePOV.sendEvent(buildTextEvent(message, aliceSession, aliceRoomId), new TestApiCallback(lock1) { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(message, aliceSession, aliceRoomId), new TestApiCallback(lock1) { @Override public void onSuccess(Void info) { results.put("sendEvent", "sendEvent"); @@ -2428,7 +2442,7 @@ public void onSuccess(byte[] info) { IMXStore store = new MXFileStore(hs, false, context); MXSession aliceSession2 = new MXSession.Builder(hs, new MXDataHandler(store, aliceCredentials2), context) - .withLegacyCryptoStore(USE_LEGACY_CRYPTO_STORE) + .withLegacyCryptoStore(mCryptoTestHelper.USE_LEGACY_CRYPTO_STORE) .build(); aliceSession2.enableCryptoWhenStarting(); @@ -2499,33 +2513,15 @@ public void onCryptoSyncComplete() { // import the e2e keys // test with a wrong password CountDownLatch lock3 = new CountDownLatch(1); - aliceSession2.getCrypto().importRoomKeys((byte[]) results.get("exportRoomKeys"), "wrong password", new TestApiCallback(lock3) { - @Override - public void onSuccess(Void info) { - results.put("importRoomKeys", "importRoomKeys"); - super.onSuccess(info); - } - - @Override - public void onNetworkError(Exception e) { - results.put("importRoomKeys_failed", "importRoomKeys_failed"); - super.onNetworkError(e); - } - - @Override - public void onMatrixError(MatrixError e) { - results.put("importRoomKeys_failed", "importRoomKeys_failed"); - super.onMatrixError(e); - } - - @Override - public void onUnexpectedError(Exception e) { - results.put("importRoomKeys_failed", "importRoomKeys_failed"); - super.onUnexpectedError(e); - } - }); + aliceSession2.getCrypto() + .importRoomKeys((byte[]) results.get("exportRoomKeys"), "wrong password", new TestApiCallback(lock3, false) { + @Override + public void onUnexpectedError(Exception e) { + results.put("importRoomKeys_failed", "importRoomKeys_failed"); + super.onUnexpectedError(e); + } + }); mTestHelper.await(lock3); - Assert.assertFalse(results.containsKey("importRoomKeys")); Assert.assertTrue(results.containsKey("importRoomKeys_failed")); // check that the message cannot be decrypted @@ -2537,9 +2533,12 @@ public void onUnexpectedError(Exception e) { Assert.assertEquals(MXCryptoError.UNKNOWN_INBOUND_SESSION_ID_ERROR_CODE, event.getCryptoError().errcode); CountDownLatch lock4 = new CountDownLatch(1); - aliceSession2.getCrypto().importRoomKeys((byte[]) results.get("exportRoomKeys"), password, new TestApiCallback(lock4) { + aliceSession2.getCrypto().importRoomKeys((byte[]) results.get("exportRoomKeys"), password, new TestApiCallback(lock4) { @Override - public void onSuccess(Void info) { + public void onSuccess(ImportRoomKeysResult info) { + Assert.assertEquals(1, info.getTotalNumberOfKeys()); + Assert.assertEquals(1, info.getSuccessfullyNumberOfImportedKeys()); + results.put("importRoomKeys", "importRoomKeys"); super.onSuccess(info); } @@ -2553,8 +2552,9 @@ public void onSuccess(Void info) { Assert.assertTrue(event.isEncrypted()); Assert.assertNotNull(event.getClearEvent()); Assert.assertNull(event.getCryptoError()); - checkEncryptedEvent(event, aliceRoomId, message, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, message, aliceSession); + cryptoTestData.clear(context); aliceSession2.clear(context); } @@ -2569,8 +2569,8 @@ public void test25_testLeftAndJoinedBob() throws Exception { final Map results = new HashMap<>(); - MXSession aliceSession = mTestHelper.createAccount(TestConstants.USER_ALICE, defaultSessionParams); - MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams); + MXSession aliceSession = mTestHelper.createAccount(TestConstants.USER_ALICE, mCryptoTestHelper.getDefaultSessionParams()); + MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, mCryptoTestHelper.getDefaultSessionParams()); CountDownLatch lock_1 = new CountDownLatch(2); @@ -2600,7 +2600,7 @@ public void onSuccess(String roomId) { Room roomFromAlicePOV = aliceSession.getDataHandler().getRoom(aliceRoomId); CountDownLatch lock1 = new CountDownLatch(1); - roomFromAlicePOV.enableEncryptionWithAlgorithm(MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM, new TestApiCallback(lock1) { + roomFromAlicePOV.enableEncryptionWithAlgorithm(CryptoConstantsKt.MXCRYPTO_ALGORITHM_MEGOLM, new TestApiCallback(lock1) { @Override public void onSuccess(Void info) { results.put("enableEncryptionWithAlgorithm", "enableEncryptionWithAlgorithm"); @@ -2634,7 +2634,7 @@ public void onEvent(Event event, EventTimeline.Direction direction, RoomState ro }; roomFromBobPOV.getTimeline().addEventTimelineListener(eventTimelineListener); - roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new SimpleApiCallback() { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // Ignore @@ -2645,7 +2645,7 @@ public void onSuccess(Void info) { Assert.assertEquals(1, receivedEvents.size()); Event event = receivedEvents.get(0); - checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); CountDownLatch lock4 = new CountDownLatch(1); roomFromBobPOV.leave(new TestApiCallback(lock4) { @@ -2662,7 +2662,7 @@ public void onSuccess(Void info) { Credentials bobCredentials = bobSession.getCredentials(); bobSession.clear(context); - MXSession bobSession2 = mTestHelper.logIntoAccount(bobSession.getMyUserId(), encryptedSessionParams); + MXSession bobSession2 = mTestHelper.logIntoAccount(bobSession.getMyUserId(), mCryptoTestHelper.getEncryptedSessionParams()); Assert.assertNotNull(bobSession2); Assert.assertTrue(bobSession2.isCryptoEnabled()); Assert.assertNotEquals(bobSession2.getCrypto().getMyDevice().deviceId, bobCredentials.deviceId); @@ -2693,7 +2693,7 @@ public void onEvent(Event event, EventTimeline.Direction direction, RoomState ro }; roomFromBobPOV2.getTimeline().addEventTimelineListener(eventTimelineListener2); - roomFromAlicePOV.sendEvent(buildTextEvent(message2FromAlice, aliceSession, aliceRoomId), new SimpleApiCallback() { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(message2FromAlice, aliceSession, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // Ignore @@ -2704,10 +2704,11 @@ public void onSuccess(Void info) { Assert.assertEquals(1, receivedEvents2.size()); event = receivedEvents2.get(0); - checkEncryptedEvent(event, aliceRoomId, message2FromAlice, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, message2FromAlice, aliceSession); - bobSession2.clear(context); aliceSession.clear(context); + bobSession.clear(context); + bobSession2.clear(context); } @Test @@ -2735,11 +2736,11 @@ public void test26_testBlackListUnverifiedDevices() throws Exception { Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Triple triple = doE2ETestWithAliceAndBobAndSamInARoom(); - final MXSession aliceSession = triple.first.first; - final String aliceRoomId = triple.first.second; - MXSession bobSession = triple.second; - MXSession samSession = triple.third; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobAndSamInARoom(); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); + final MXSession samSession = cryptoTestData.getThirdSession(); final String messageFromAlice = "Hello I'm Alice!"; @@ -2753,7 +2754,7 @@ public void test26_testBlackListUnverifiedDevices() throws Exception { CountDownLatch lock1 = new CountDownLatch(1); - roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new TestApiCallback(lock1) { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new TestApiCallback(lock1, false) { @Override public void onMatrixError(MatrixError e) { results.put("sendEventError", e); @@ -2796,7 +2797,7 @@ public void onSuccess(Void info) { @Override public void onLiveEvent(Event event, RoomState roomState) { if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) { - checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); results.put("onLiveEventBob1", "onLiveEvent"); lock3.countDown(); @@ -2808,7 +2809,7 @@ public void onLiveEvent(Event event, RoomState roomState) { @Override public void onLiveEvent(Event event, RoomState roomState) { if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) { - checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession); results.put("onLiveEventSam1", "onLiveEvent"); lock3.countDown(); @@ -2835,7 +2836,7 @@ public void onToDeviceEvent(Event event) { roomFromBobPOV.addEventListener(eventListenerBob1); roomFromSamPOV.addEventListener(eventListenerSam1); - roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new TestApiCallback(lock3) { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new TestApiCallback(lock3) { @Override public void onSuccess(Void info) { lock3.countDown(); @@ -2859,7 +2860,7 @@ public void onSuccess(Void info) { @Override public void onLiveEvent(Event event, RoomState roomState) { if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) { - checkEncryptedEvent(event, aliceRoomId, activeMessage.get(0), aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, activeMessage.get(0), aliceSession); results.put("eventListenerBob2", "onLiveEvent"); activeLock.get(0).countDown(); @@ -2874,7 +2875,7 @@ public void onLiveEvent(Event event, RoomState roomState) { @Override public void onLiveEvent(Event event, RoomState roomState) { if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) { - checkEncryptedEvent(event, aliceRoomId, activeMessage.get(0), aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, activeMessage.get(0), aliceSession); results.put("eventListenerSam2", "onLiveEvent"); activeLock.get(0).countDown(); @@ -2912,7 +2913,7 @@ public void onSuccess(Void info) { activeMessage.clear(); activeMessage.add("message 1"); - roomFromAlicePOV.sendEvent(buildTextEvent(activeMessage.get(0), aliceSession, aliceRoomId), new TestApiCallback(lock5)); + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(activeMessage.get(0), aliceSession, aliceRoomId), new TestApiCallback(lock5)); mTestHelper.await(lock5); Assert.assertFalse(results.containsKey("eventListenerBob2")); @@ -2942,7 +2943,7 @@ public void onSuccess(Void info) { activeMessage.clear(); activeMessage.add("message 2"); - roomFromAlicePOV.sendEvent(buildTextEvent(activeMessage.get(0), aliceSession, aliceRoomId), new TestApiCallback(lock7)); + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(activeMessage.get(0), aliceSession, aliceRoomId), new TestApiCallback(lock7)); mTestHelper.await(lock7); Assert.assertTrue(results.containsKey("eventListenerBob2")); @@ -2985,7 +2986,7 @@ public void onSuccess(Void info) { activeMessage.clear(); activeMessage.add("message 3"); - roomFromAlicePOV.sendEvent(buildTextEvent(activeMessage.get(0), aliceSession, aliceRoomId), new TestApiCallback(lock10)); + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(activeMessage.get(0), aliceSession, aliceRoomId), new TestApiCallback(lock10)); mTestHelper.await(lock10); Assert.assertTrue(results.containsKey("eventListenerBob2")); @@ -3013,7 +3014,7 @@ public void onSuccess(Void info) { activeMessage.clear(); activeMessage.add("message 3"); - roomFromAlicePOV.sendEvent(buildTextEvent(activeMessage.get(0), aliceSession, aliceRoomId), new TestApiCallback(lock12)); + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(activeMessage.get(0), aliceSession, aliceRoomId), new TestApiCallback(lock12)); mTestHelper.await(lock12); Assert.assertTrue(results.containsKey("eventListenerBob2")); @@ -3021,7 +3022,7 @@ public void onSuccess(Void info) { Assert.assertFalse(results.containsKey("eventListenerEncyptedBob2")); Assert.assertFalse(results.containsKey("eventListenerEncyptedSam2")); - bobSession.clear(context); + cryptoTestData.clear(context); } @Test @@ -3039,8 +3040,8 @@ public void test27_testEnableEncryptionAfterNonEncryptedMessages() throws Except final String messageFromAlice = "Hello I'm Alice!"; final String message2FromAlice = "I'm still Alice!"; - MXSession aliceSession = mTestHelper.createAccount(TestConstants.USER_ALICE, defaultSessionParams); - MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams); + MXSession aliceSession = mTestHelper.createAccount(TestConstants.USER_ALICE, mCryptoTestHelper.getDefaultSessionParams()); + MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, mCryptoTestHelper.getDefaultSessionParams()); CountDownLatch lock00b = new CountDownLatch(2); aliceSession.enableCrypto(true, new TestApiCallback(lock00b) { @@ -3092,7 +3093,7 @@ public void onSuccess(String info) { Room roomFromAlicePOV = aliceSession.getDataHandler().getRoom(aliceRoomId); CountDownLatch lock2 = new CountDownLatch(1); - roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new TestApiCallback(lock2) { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new TestApiCallback(lock2) { @Override public void onSuccess(Void info) { results.put("sendEvent1", "sendEvent1"); @@ -3106,14 +3107,14 @@ public void onSuccess(Void info) { Credentials bobCredentials = bobSession.getCredentials(); bobSession.clear(context); - MXSession bobSession2 = mTestHelper.logIntoAccount(bobSession.getMyUserId(), encryptedSessionParams); + MXSession bobSession2 = mTestHelper.logIntoAccount(bobSession.getMyUserId(), mCryptoTestHelper.getEncryptedSessionParams()); Assert.assertNotNull(bobSession2); Assert.assertTrue(bobSession2.isCryptoEnabled()); Assert.assertNotEquals(bobSession2.getCrypto().getMyDevice().deviceId, bobCredentials.deviceId); bobSession2.getCrypto().setWarnOnUnknownDevices(false); CountDownLatch lock3 = new CountDownLatch(1); - roomFromAlicePOV.enableEncryptionWithAlgorithm(MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM, new TestApiCallback(lock3) { + roomFromAlicePOV.enableEncryptionWithAlgorithm(CryptoConstantsKt.MXCRYPTO_ALGORITHM_MEGOLM, new TestApiCallback(lock3) { @Override public void onSuccess(Void info) { results.put("enableEncryptionWithAlgorithm", "enableEncryptionWithAlgorithm"); @@ -3139,7 +3140,7 @@ public void onEvent(Event event, EventTimeline.Direction direction, RoomState ro }; roomFromBobPOV2.getTimeline().addEventTimelineListener(eventTimelineListener2); - roomFromAlicePOV.sendEvent(buildTextEvent(message2FromAlice, aliceSession, aliceRoomId), new SimpleApiCallback() { + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(message2FromAlice, aliceSession, aliceRoomId), new SimpleApiCallback() { @Override public void onSuccess(Void info) { // Ignore @@ -3150,10 +3151,11 @@ public void onSuccess(Void info) { Assert.assertEquals(1, receivedEvents2.size()); Event event = receivedEvents2.get(0); - checkEncryptedEvent(event, aliceRoomId, message2FromAlice, aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, message2FromAlice, aliceSession); - bobSession2.clear(context); aliceSession.clear(context); + bobSession.clear(context); + bobSession2.clear(context); } // Test for https://github.com/vector-im/riot-web/issues/4983 @@ -3168,10 +3170,10 @@ public void test28_testLeftBobAndAliceWithNewDevice() throws Exception { Context context = InstrumentationRegistry.getContext(); final Map results = new HashMap<>(); - Pair pair = doE2ETestWithAliceAndBobInARoomWithEncryptedMessages(true); - MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - final MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages(true); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); // - Bob leaves the room, so stops getting updates CountDownLatch lock1 = new CountDownLatch(1); @@ -3189,7 +3191,7 @@ public void onSuccess(Void info) { Assert.assertTrue(results.containsKey("lock1")); // - Alice adds a new device - final MXSession aliceSession2 = mTestHelper.logIntoAccount(aliceSession.getMyUserId(), encryptedSessionParams); + final MXSession aliceSession2 = mTestHelper.logIntoAccount(aliceSession.getMyUserId(), mCryptoTestHelper.getEncryptedSessionParams()); Assert.assertNotNull(aliceSession2); // - Alice and Bob start sharing a room again @@ -3209,7 +3211,7 @@ public void onSuccess(String info) { Room roomFromAlicePOV = aliceSession2.getDataHandler().getRoom(aliceRoomId2[0]); CountDownLatch lock4 = new CountDownLatch(1); - roomFromAlicePOV.enableEncryptionWithAlgorithm(MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM, new TestApiCallback(lock4) { + roomFromAlicePOV.enableEncryptionWithAlgorithm(CryptoConstantsKt.MXCRYPTO_ALGORITHM_MEGOLM, new TestApiCallback(lock4) { @Override public void onSuccess(Void info) { results.put("lock4", "lock4"); @@ -3238,7 +3240,7 @@ public void onSuccess(String info) { @Override public void onLiveEvent(Event event, RoomState roomState) { if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) { - checkEncryptedEvent(event, aliceRoomId2[0], messageFromBob, bobSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId2[0], messageFromBob, bobSession); results.put("lock6", "lock6"); lock6.countDown(); @@ -3248,13 +3250,12 @@ public void onLiveEvent(Event event, RoomState roomState) { roomFromAlicePOV.addEventListener(eventListener); - roomFromBobPOV.sendEvent(buildTextEvent(messageFromBob, bobSession, aliceRoomId2[0]), new TestApiCallback(lock6)); + roomFromBobPOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromBob, bobSession, aliceRoomId2[0]), new TestApiCallback(lock6)); mTestHelper.await(lock6); Assert.assertTrue(results.containsKey("lock6")); - bobSession.clear(context); - aliceSession.clear(context); + cryptoTestData.clear(context); aliceSession2.clear(context); } @@ -3266,11 +3267,12 @@ public void onLiveEvent(Event event, RoomState roomState) { @Test public void test29_testAliceAndBobInAEncryptedRoomWithReplyTo() throws Exception { Log.e(LOG_TAG, "test08_testAliceAndBobInAEncryptedRoom2"); + Context context = InstrumentationRegistry.getContext(); - Pair pair = doE2ETestWithAliceAndBobInARoom(true); - final MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - final MXSession bobSession = pair.second; + CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true); + final MXSession aliceSession = cryptoTestData.getFirstSession(); + final String aliceRoomId = cryptoTestData.getRoomId(); + final MXSession bobSession = cryptoTestData.getSecondSession(); bobSession.getCrypto().setWarnOnUnknownDevices(false); aliceSession.getCrypto().setWarnOnUnknownDevices(false); @@ -3295,7 +3297,7 @@ public void onLiveEvent(Event event, RoomState roomState) { if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE) && !TextUtils.equals(event.getSender(), bobSession.getMyUserId())) { bobReceivedEvents.add(event); - checkEncryptedEvent(event, aliceRoomId, messagesFromAlice.get(nbReceivedMessagesFromAlice[0]), aliceSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, mCryptoTestHelper.getMessagesFromAlice().get(nbReceivedMessagesFromAlice[0]), aliceSession); nbReceivedMessagesFromAlice[0]++; list.get(list.size() - 1).countDown(); @@ -3312,12 +3314,12 @@ public void onLiveEvent(Event event, RoomState roomState) { try { // "In reply to" format for body String expectedMessage = "> <" + aliceSession.getMyUserId() + "> " - + messagesFromAlice.get(nbReceivedMessagesFromAlice[0] - 1) + + mCryptoTestHelper.getMessagesFromAlice().get(nbReceivedMessagesFromAlice[0] - 1) + "\n\n" - + messagesFromBob.get(nbReceivedMessagesFromBob[0]); + + mCryptoTestHelper.getMessagesFromBob().get(nbReceivedMessagesFromBob[0]); - checkEncryptedEvent(event, aliceRoomId, expectedMessage, bobSession); + mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, expectedMessage, bobSession); nbReceivedMessagesFromBob[0]++; @@ -3351,7 +3353,7 @@ public void onToDeviceEvent(Event event) { }); // Alice sends a first event - roomFromAlicePOV.sendEvent(buildTextEvent(messagesFromAlice.get(nbReceivedMessagesFromAlice[0]), aliceSession, aliceRoomId), callback); + roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(mCryptoTestHelper.getMessagesFromAlice().get(nbReceivedMessagesFromAlice[0]), aliceSession, aliceRoomId), callback); mTestHelper.await(list.get(list.size() - 1)); Assert.assertTrue(results.containsKey("onToDeviceEvent")); Assert.assertEquals(1, nbReceivedMessagesFromAlice[0]); @@ -3360,7 +3362,7 @@ public void onToDeviceEvent(Event event) { Assert.assertTrue(roomFromBobPOV.canReplyTo(bobReceivedEvents.get(0))); list.add(new CountDownLatch(1)); - roomFromBobPOV.sendTextMessage(messagesFromBob.get(nbReceivedMessagesFromBob[0]), null, Message.MSGTYPE_TEXT, bobReceivedEvents.get(0), null); + roomFromBobPOV.sendTextMessage(mCryptoTestHelper.getMessagesFromBob().get(nbReceivedMessagesFromBob[0]), null, Message.MSGTYPE_TEXT, bobReceivedEvents.get(0), null); mTestHelper.await(list.get(list.size() - 1)); Assert.assertEquals(1, nbReceivedMessagesFromBob[0]); @@ -3381,393 +3383,15 @@ public void onToDeviceEvent(Event event) { // Check that the event id matches Assert.assertEquals(bobReceivedEvents.get(0).eventId, relatesTo.dict.get("event_id")); + + cryptoTestData.clear(context); } @Test public void test30_aliceBobStressTest() throws Exception { for (int i = 0; i < 10; i++) { Log.e(LOG_TAG, "test30_aliceBobFailure: attempt " + i); - doE2ETestWithAliceAndBobInARoom(true); - } - } - - //============================================================================================================== - // private test routines - //============================================================================================================== - - - /** - * @return alice session - * @throws Exception - */ - private SessionAndRoomId doE2ETestWithAliceInARoom() throws Exception { - final Map results = new HashMap<>(); - MXSession aliceSession = mTestHelper.createAccount(TestConstants.USER_ALICE, defaultSessionParams); - CountDownLatch lock0 = new CountDownLatch(1); - - aliceSession.enableCrypto(true, new TestApiCallback(lock0) { - @Override - public void onSuccess(Void info) { - results.put("enableCrypto", "enableCrypto"); - super.onSuccess(info); - } - }); - mTestHelper.await(lock0); - Assert.assertTrue(results.containsKey("enableCrypto")); - - final String[] roomId = {null}; - CountDownLatch lock1 = new CountDownLatch(1); - - aliceSession.createRoom(new TestApiCallback(lock1) { - @Override - public void onSuccess(String createdRoomId) { - roomId[0] = createdRoomId; - super.onSuccess(createdRoomId); - } - }); - - mTestHelper.await(lock1); - Assert.assertNotNull(roomId[0]); - - Room room = aliceSession.getDataHandler().getRoom(roomId[0]); - - CountDownLatch lock2 = new CountDownLatch(1); - room.enableEncryptionWithAlgorithm(MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM, new TestApiCallback(lock2) { - @Override - public void onSuccess(Void info) { - results.put("enableEncryptionWithAlgorithm", "enableEncryptionWithAlgorithm"); - super.onSuccess(info); - } - }); - mTestHelper.await(lock2); - Assert.assertTrue(results.containsKey("enableEncryptionWithAlgorithm")); - - return new SessionAndRoomId(aliceSession, roomId[0]); - } - - /** - * @param cryptedBob - * @return alice and bob sessions - * @throws Exception - */ - private Pair doE2ETestWithAliceAndBobInARoom(boolean cryptedBob) throws Exception { - final Map statuses = new HashMap<>(); - - SessionAndRoomId sessionAndRoomId = doE2ETestWithAliceInARoom(); - MXSession aliceSession = sessionAndRoomId.first; - final String aliceRoomId = sessionAndRoomId.second; - - Room roomFromAlicePOV = aliceSession.getDataHandler().getRoom(aliceRoomId); - - MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams); - CountDownLatch lock0 = new CountDownLatch(1); - - bobSession.enableCrypto(cryptedBob, new TestApiCallback(lock0) { - @Override - public void onSuccess(Void info) { - statuses.put("enableCrypto", "enableCrypto"); - super.onSuccess(info); - } - }); - mTestHelper.await(lock0); - - final CountDownLatch lock1 = new CountDownLatch(2); - - MXEventListener bobEventListener = new MXEventListener() { - @Override - public void onNewRoom(String roomId) { - if (TextUtils.equals(roomId, aliceRoomId)) { - if (!statuses.containsKey("onNewRoom")) { - statuses.put("onNewRoom", "onNewRoom"); - lock1.countDown(); - } - } - } - }; - - bobSession.getDataHandler().addListener(bobEventListener); - - roomFromAlicePOV.invite(bobSession.getMyUserId(), new TestApiCallback(lock1) { - @Override - public void onSuccess(Void info) { - statuses.put("invite", "invite"); - super.onSuccess(info); - } - }); - - mTestHelper.await(lock1); - - Assert.assertTrue(statuses.containsKey("invite") && statuses.containsKey("onNewRoom")); - - bobSession.getDataHandler().removeListener(bobEventListener); - - final CountDownLatch lock2 = new CountDownLatch(2); - - bobSession.joinRoom(aliceRoomId, new TestApiCallback(lock2) { - @Override - public void onSuccess(String info) { - statuses.put("joinRoom", "joinRoom"); - super.onSuccess(info); - } - - @Override - public void onNetworkError(Exception e) { - statuses.put("onNetworkError", e.getMessage()); - super.onNetworkError(e); - } - - @Override - public void onMatrixError(MatrixError e) { - statuses.put("onMatrixError", e.getMessage()); - super.onMatrixError(e); - } - - @Override - public void onUnexpectedError(Exception e) { - statuses.put("onUnexpectedError", e.getMessage()); - super.onUnexpectedError(e); - } - }); - - roomFromAlicePOV.addEventListener(new MXEventListener() { - @Override - public void onLiveEvent(Event event, RoomState roomState) { - if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_STATE_ROOM_MEMBER)) { - JsonObject contentToConsider = event.getContentAsJsonObject(); - RoomMember member = JsonUtils.toRoomMember(contentToConsider); - - if (TextUtils.equals(member.membership, RoomMember.MEMBERSHIP_JOIN)) { - statuses.put("AliceJoin", "AliceJoin"); - lock2.countDown(); - } - } - } - }); - - mTestHelper.await(lock2); - - // Ensure bob can send messages to the room - Room roomFromBobPOV = bobSession.getDataHandler().getRoom(aliceRoomId); - Assert.assertNotNull(roomFromBobPOV.getState().getPowerLevels()); - Assert.assertTrue(roomFromBobPOV.getState().getPowerLevels().maySendMessage(bobSession.getMyUserId())); - - Assert.assertTrue(statuses + "", statuses.containsKey("joinRoom")); - Assert.assertTrue(statuses + "", statuses.containsKey("AliceJoin")); - - bobSession.getDataHandler().removeListener(bobEventListener); - - return new Pair<>(sessionAndRoomId, bobSession); - } - - /** - * @return Alice, Bbob and sam session - * @throws Exception - */ - private Triple doE2ETestWithAliceAndBobAndSamInARoom() throws Exception { - final Map statuses = new HashMap<>(); - - Pair pair = doE2ETestWithAliceAndBobInARoom(true); - MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - - Room room = aliceSession.getDataHandler().getRoom(aliceRoomId); - - MXSession samSession = mTestHelper.createAccount(TestConstants.USER_SAM, defaultSessionParams); - CountDownLatch lock0 = new CountDownLatch(1); - - samSession.enableCrypto(true, new TestApiCallback(lock0) { - @Override - public void onSuccess(Void info) { - statuses.put("enableCrypto", "enableCrypto"); - super.onSuccess(info); - } - }); - mTestHelper.await(lock0); - - final CountDownLatch lock1 = new CountDownLatch(2); - - MXEventListener samEventListener = new MXEventListener() { - @Override - public void onNewRoom(String roomId) { - if (TextUtils.equals(roomId, aliceRoomId)) { - if (!statuses.containsKey("onNewRoom")) { - statuses.put("onNewRoom", "onNewRoom"); - lock1.countDown(); - } - } - } - }; - - samSession.getDataHandler().addListener(samEventListener); - - room.invite(samSession.getMyUserId(), new TestApiCallback(lock1) { - @Override - public void onSuccess(Void info) { - statuses.put("invite", "invite"); - super.onSuccess(info); - } - }); - - mTestHelper.await(lock1); - - Assert.assertTrue(statuses.containsKey("invite") && statuses.containsKey("onNewRoom")); - - samSession.getDataHandler().removeListener(samEventListener); - - CountDownLatch lock2 = new CountDownLatch(1); - - samSession.joinRoom(aliceRoomId, new TestApiCallback(lock2) { - @Override - public void onSuccess(String info) { - statuses.put("joinRoom", "joinRoom"); - super.onSuccess(info); - } - }); - - mTestHelper.await(lock2); - Assert.assertTrue(statuses.containsKey("joinRoom")); - - // wait the initial sync - SystemClock.sleep(1000); - - samSession.getDataHandler().removeListener(samEventListener); - - return new Triple<>(pair, samSession); - } - - private Event buildTextEvent(String text, MXSession session, String roomId) { - Message message = new Message(); - message.msgtype = Message.MSGTYPE_TEXT; - message.body = text; - - return new Event(message, session.getCredentials().userId, roomId); - } - - /** - * @param cryptedBob - * @return Alice and Bob sessions - * @throws Exception - */ - private Pair doE2ETestWithAliceAndBobInARoomWithEncryptedMessages(boolean cryptedBob) throws Exception { - Pair pair = doE2ETestWithAliceAndBobInARoom(cryptedBob); - final MXSession aliceSession = pair.first.first; - final String aliceRoomId = pair.first.second; - final MXSession bobSession = pair.second; - - if (null != bobSession.getCrypto()) { - bobSession.getCrypto().setWarnOnUnknownDevices(false); + mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true); } - - if (null != aliceSession.getCrypto()) { - aliceSession.getCrypto().setWarnOnUnknownDevices(false); - } - - final Room roomFromBobPOV = bobSession.getDataHandler().getRoom(aliceRoomId); - final Room roomFromAlicePOV = aliceSession.getDataHandler().getRoom(aliceRoomId); - - final int[] messagesCount = {0}; - - final List list = new ArrayList<>(); - - MXEventListener bobEventsListener = new MXEventListener() { - @Override - public void onLiveEvent(Event event, RoomState roomState) { - if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE) && !TextUtils.equals(event.getSender(), bobSession.getMyUserId())) { - messagesCount[0]++; - list.get(0).countDown(); - } - } - }; - - roomFromBobPOV.addEventListener(bobEventsListener); - - ApiCallback callback = new SimpleApiCallback() { - @Override - public void onSuccess(Void info) { - list.get(0).countDown(); - } - }; - - final Map results = new HashMap<>(); - - CountDownLatch lock = new CountDownLatch(3); - list.clear(); - list.add(lock); - - bobSession.getDataHandler().addListener(new MXEventListener() { - @Override - public void onToDeviceEvent(Event event) { - results.put("onToDeviceEvent", event); - list.get(0).countDown(); - } - }); - - roomFromAlicePOV.sendEvent(buildTextEvent(messagesFromAlice.get(0), aliceSession, aliceRoomId), callback); - mTestHelper.await(lock); - Assert.assertTrue(results.containsKey("onToDeviceEvent")); - Assert.assertEquals(1, messagesCount[0]); - - lock = new CountDownLatch(1); - list.clear(); - list.add(lock); - roomFromBobPOV.sendEvent(buildTextEvent(messagesFromBob.get(0), bobSession, aliceRoomId), callback); - // android does not echo the messages sent from itself - messagesCount[0]++; - mTestHelper.await(lock); - Assert.assertEquals(2, messagesCount[0]); - - lock = new CountDownLatch(1); - list.clear(); - list.add(lock); - roomFromBobPOV.sendEvent(buildTextEvent(messagesFromBob.get(1), bobSession, aliceRoomId), callback); - // android does not echo the messages sent from itself - messagesCount[0]++; - mTestHelper.await(lock); - Assert.assertEquals(3, messagesCount[0]); - - lock = new CountDownLatch(1); - list.clear(); - list.add(lock); - roomFromBobPOV.sendEvent(buildTextEvent(messagesFromBob.get(2), bobSession, aliceRoomId), callback); - // android does not echo the messages sent from itself - messagesCount[0]++; - mTestHelper.await(lock); - Assert.assertEquals(4, messagesCount[0]); - - lock = new CountDownLatch(2); - list.clear(); - list.add(lock); - roomFromAlicePOV.sendEvent(buildTextEvent(messagesFromAlice.get(1), aliceSession, aliceRoomId), callback); - mTestHelper.await(lock); - Assert.assertEquals(5, messagesCount[0]); - - return pair; - } - - private void checkEncryptedEvent(Event event, String roomId, String clearMessage, MXSession senderSession) { - Assert.assertEquals(Event.EVENT_TYPE_MESSAGE_ENCRYPTED, event.getWireType()); - Assert.assertNotNull(event.getWireContent()); - - JsonObject eventWireContent = event.getWireContent().getAsJsonObject(); - Assert.assertNotNull(eventWireContent); - - Assert.assertNull(eventWireContent.get("body")); - Assert.assertEquals(MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM, eventWireContent.get("algorithm").getAsString()); - - Assert.assertNotNull(eventWireContent.get("ciphertext")); - Assert.assertNotNull(eventWireContent.get("session_id")); - Assert.assertNotNull(eventWireContent.get("sender_key")); - - Assert.assertEquals(senderSession.getCredentials().deviceId, eventWireContent.get("device_id").getAsString()); - - Assert.assertNotNull(event.eventId); - Assert.assertEquals(roomId, event.roomId); - Assert.assertEquals(Event.EVENT_TYPE_MESSAGE, event.getType()); - Assert.assertTrue(event.getAge() < 10000); - - JsonObject eventContent = event.getContentAsJsonObject(); - Assert.assertNotNull(eventContent); - Assert.assertEquals(clearMessage, eventContent.get("body").getAsString()); - Assert.assertEquals(senderSession.getMyUserId(), event.sender); } } diff --git a/matrix-sdk/src/main/java/org/matrix/androidsdk/MXSession.java b/matrix-sdk/src/main/java/org/matrix/androidsdk/MXSession.java index fb13f562c..91d387dda 100644 --- a/matrix-sdk/src/main/java/org/matrix/androidsdk/MXSession.java +++ b/matrix-sdk/src/main/java/org/matrix/androidsdk/MXSession.java @@ -2278,6 +2278,7 @@ public Map getUserWidgets() { * The module that manages E2E encryption. * Null if the feature is not enabled */ + @Nullable private MXCrypto mCrypto; /** @@ -2369,7 +2370,7 @@ public void checkCrypto() { return; } - mCrypto = new MXCrypto(MXSession.this, mCryptoStore, sCryptoConfig); + mCrypto = new MXCrypto(this, mCryptoStore, sCryptoConfig); mDataHandler.setCrypto(mCrypto); // the room summaries are not stored with decrypted content decryptRoomSummaries(); diff --git a/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/CryptoConstants.kt b/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/CryptoConstants.kt new file mode 100644 index 000000000..c80ee8feb --- /dev/null +++ b/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/CryptoConstants.kt @@ -0,0 +1,32 @@ +/* + * Copyright 2018 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.androidsdk.crypto + +/** + * Matrix algorithm value for olm. + */ +const val MXCRYPTO_ALGORITHM_OLM = "m.olm.v1.curve25519-aes-sha2" + +/** + * Matrix algorithm value for megolm. + */ +const val MXCRYPTO_ALGORITHM_MEGOLM = "m.megolm.v1.aes-sha2" + +/** + * Matrix algorithm value for megolm keys backup. + */ +const val MXCRYPTO_ALGORITHM_MEGOLM_BACKUP = "m.megolm_backup.v1.curve25519-aes-sha2" diff --git a/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/MXCrypto.java b/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/MXCrypto.java index 626473f56..e9a703a16 100755 --- a/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/MXCrypto.java +++ b/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/MXCrypto.java @@ -672,8 +672,8 @@ private void updateOneTimeKeyCount(int currentCount) { */ public MXDeviceInfo deviceWithIdentityKey(final String senderKey, final String userId, final String algorithm) { if (!hasBeenReleased()) { - if (!TextUtils.equals(algorithm, MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM) - && !TextUtils.equals(algorithm, MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_OLM)) { + if (!TextUtils.equals(algorithm, CryptoConstantsKt.MXCRYPTO_ALGORITHM_MEGOLM) + && !TextUtils.equals(algorithm, CryptoConstantsKt.MXCRYPTO_ALGORITHM_OLM)) { // We only deal in olm keys return null; } @@ -1508,7 +1508,7 @@ public Map encryptMessage(Map payloadFields, Lis Map res = new HashMap<>(); - res.put("algorithm", MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_OLM); + res.put("algorithm", CryptoConstantsKt.MXCRYPTO_ALGORITHM_OLM); res.put("sender_key", mOlmDevice.getDeviceCurve25519Key()); res.put("ciphertext", ciphertext); diff --git a/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/MXCryptoAlgorithms.java b/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/MXCryptoAlgorithms.java index 23f826656..be914b0a5 100755 --- a/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/MXCryptoAlgorithms.java +++ b/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/MXCryptoAlgorithms.java @@ -32,16 +32,6 @@ public class MXCryptoAlgorithms { private static final String LOG_TAG = MXCryptoAlgorithms.class.getSimpleName(); - /** - * Matrix algorithm tag for olm. - */ - public static final String MXCRYPTO_ALGORITHM_OLM = "m.olm.v1.curve25519-aes-sha2"; - - /** - * Matrix algorithm tag for megolm. - */ - public static final String MXCRYPTO_ALGORITHM_MEGOLM = "m.megolm.v1.aes-sha2"; - // encryptors map private final Map> mEncryptors; @@ -69,14 +59,14 @@ private MXCryptoAlgorithms() { // encryptos mEncryptors = new HashMap<>(); try { - mEncryptors.put(MXCRYPTO_ALGORITHM_MEGOLM, + mEncryptors.put(CryptoConstantsKt.MXCRYPTO_ALGORITHM_MEGOLM, (Class) Class.forName("org.matrix.androidsdk.crypto.algorithms.megolm.MXMegolmEncryption")); } catch (Exception e) { Log.e(LOG_TAG, "## MXCryptoAlgorithms() : fails to add MXCRYPTO_ALGORITHM_MEGOLM " + e.getMessage(), e); } try { - mEncryptors.put(MXCRYPTO_ALGORITHM_OLM, + mEncryptors.put(CryptoConstantsKt.MXCRYPTO_ALGORITHM_OLM, (Class) Class.forName("org.matrix.androidsdk.crypto.algorithms.olm.MXOlmEncryption")); } catch (Exception e) { Log.e(LOG_TAG, "## MXCryptoAlgorithms() : fails to add MXCRYPTO_ALGORITHM_OLM " + e.getMessage(), e); @@ -84,14 +74,14 @@ private MXCryptoAlgorithms() { mDecryptors = new HashMap<>(); try { - mDecryptors.put(MXCRYPTO_ALGORITHM_MEGOLM, + mDecryptors.put(CryptoConstantsKt.MXCRYPTO_ALGORITHM_MEGOLM, (Class) Class.forName("org.matrix.androidsdk.crypto.algorithms.megolm.MXMegolmDecryption")); } catch (Exception e) { Log.e(LOG_TAG, "## MXCryptoAlgorithms() : fails to add MXCRYPTO_ALGORITHM_MEGOLM " + e.getMessage(), e); } try { - mDecryptors.put(MXCRYPTO_ALGORITHM_OLM, + mDecryptors.put(CryptoConstantsKt.MXCRYPTO_ALGORITHM_OLM, (Class) Class.forName("org.matrix.androidsdk.crypto.algorithms.olm.MXOlmDecryption")); } catch (Exception e) { Log.e(LOG_TAG, "## MXCryptoAlgorithms() : fails to add MXCRYPTO_ALGORITHM_OLM " + e.getMessage(), e); diff --git a/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/MXOlmDevice.java b/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/MXOlmDevice.java index 245f622e1..63b18c7b5 100755 --- a/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/MXOlmDevice.java +++ b/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/MXOlmDevice.java @@ -272,7 +272,7 @@ public String createOutboundSession(String theirIdentityKey, String theirOneTime * @param theirDeviceIdentityKey the remote user's Curve25519 identity key. * @param messageType the message_type field from the received message (must be 0). * @param ciphertext base64-encoded body from the received message. - * @return {{payload: string, session_id: string}} decrypted payload, andsession id of new session. + * @return {{payload: string, session_id: string}} decrypted payload, and session id of new session. */ public Map createInboundSession(String theirDeviceIdentityKey, int messageType, String ciphertext) { @@ -644,7 +644,7 @@ public void removeInboundGroupSession(String sessionId, String sessionKey) { * Decrypt a received message with an inbound group session. * * @param body the base64-encoded body of the encrypted message. - * @param roomId theroom in which the message was received. + * @param roomId the room in which the message was received. * @param timeline the id of the timeline where the event is decrypted. It is used to prevent replay attack. * @param sessionId the session identifier. * @param senderKey the base64-encoded curve25519 key of the sender. diff --git a/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/algorithms/megolm/MXMegolmEncryption.java b/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/algorithms/megolm/MXMegolmEncryption.java index 54f3705e1..a5323db47 100644 --- a/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/algorithms/megolm/MXMegolmEncryption.java +++ b/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/algorithms/megolm/MXMegolmEncryption.java @@ -23,8 +23,8 @@ import com.google.gson.JsonElement; import org.matrix.androidsdk.MXSession; +import org.matrix.androidsdk.crypto.CryptoConstantsKt; import org.matrix.androidsdk.crypto.MXCrypto; -import org.matrix.androidsdk.crypto.MXCryptoAlgorithms; import org.matrix.androidsdk.crypto.MXCryptoError; import org.matrix.androidsdk.crypto.MXOlmDevice; import org.matrix.androidsdk.crypto.algorithms.IMXEncrypting; @@ -427,7 +427,7 @@ private void shareUserDevicesKey(final MXOutboundSessionInfo session, final int chainIndex = mCrypto.getOlmDevice().getMessageIndex(session.mSessionId); Map submap = new HashMap<>(); - submap.put("algorithm", MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM); + submap.put("algorithm", CryptoConstantsKt.MXCRYPTO_ALGORITHM_MEGOLM); submap.put("room_id", mRoomId); submap.put("session_id", session.mSessionId); submap.put("session_key", sessionKey); @@ -611,7 +611,7 @@ private void processPendingEncryptions(MXOutboundSessionInfo session) { String ciphertext = mCrypto.getOlmDevice().encryptGroupMessage(session.mSessionId, payloadString); final Map map = new HashMap<>(); - map.put("algorithm", MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM); + map.put("algorithm", CryptoConstantsKt.MXCRYPTO_ALGORITHM_MEGOLM); map.put("sender_key", mCrypto.getOlmDevice().getDeviceCurve25519Key()); map.put("ciphertext", ciphertext); map.put("session_id", session.mSessionId); diff --git a/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/data/MXOlmInboundGroupSession2.java b/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/data/MXOlmInboundGroupSession2.java index dcdeb9544..c1238be71 100755 --- a/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/data/MXOlmInboundGroupSession2.java +++ b/matrix-sdk/src/main/java/org/matrix/androidsdk/crypto/data/MXOlmInboundGroupSession2.java @@ -19,7 +19,7 @@ import android.text.TextUtils; -import org.matrix.androidsdk.crypto.MXCryptoAlgorithms; +import org.matrix.androidsdk.crypto.CryptoConstantsKt; import org.matrix.androidsdk.util.Log; import org.matrix.olm.OlmInboundGroupSession; @@ -36,7 +36,7 @@ */ public class MXOlmInboundGroupSession2 implements Serializable { // - private static final String LOG_TAG = "OlmInboundGroupSession"; + private static final String LOG_TAG = MXOlmInboundGroupSession2.class.getSimpleName(); // define a serialVersionUID to avoid having to redefine the class after updates private static final long serialVersionUID = 201702011617L; @@ -128,7 +128,7 @@ public Map exportKeys() { map.put("room_id", mRoomId); map.put("session_id", mSession.sessionIdentifier()); map.put("session_key", mSession.export(mSession.getFirstKnownIndex())); - map.put("algorithm", MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM); + map.put("algorithm", CryptoConstantsKt.MXCRYPTO_ALGORITHM_MEGOLM); } catch (Exception e) { map = null; Log.e(LOG_TAG, "## export() : senderKey " + mSenderKey + " failed " + e.getMessage(), e); diff --git a/matrix-sdk/src/main/java/org/matrix/androidsdk/data/RoomState.java b/matrix-sdk/src/main/java/org/matrix/androidsdk/data/RoomState.java index 77816f763..af9b915ed 100644 --- a/matrix-sdk/src/main/java/org/matrix/androidsdk/data/RoomState.java +++ b/matrix-sdk/src/main/java/org/matrix/androidsdk/data/RoomState.java @@ -174,7 +174,7 @@ public class RoomState implements Externalizable { private final Map mThirdPartyInvites = new HashMap<>(); /** - * Cache for [self memberWithThirdPartyInviteToken]. + * Cache for memberWithThirdPartyInviteToken. * The key is the 3pid invite token. */ private final Map mMembersWithThirdPartyInviteTokenCache = new HashMap<>(); diff --git a/matrix-sdk/src/main/java/org/matrix/androidsdk/data/cryptostore/IMXCryptoStore.java b/matrix-sdk/src/main/java/org/matrix/androidsdk/data/cryptostore/IMXCryptoStore.java index d53c01bf1..d30ae3be1 100644 --- a/matrix-sdk/src/main/java/org/matrix/androidsdk/data/cryptostore/IMXCryptoStore.java +++ b/matrix-sdk/src/main/java/org/matrix/androidsdk/data/cryptostore/IMXCryptoStore.java @@ -1,5 +1,6 @@ /* * Copyright 2016 OpenMarket Ltd + * Copyright 2018 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk/src/main/java/org/matrix/androidsdk/rest/callback/ApiFailureCallback.java b/matrix-sdk/src/main/java/org/matrix/androidsdk/rest/callback/ApiFailureCallback.java index 0a55bd955..5828a91e4 100644 --- a/matrix-sdk/src/main/java/org/matrix/androidsdk/rest/callback/ApiFailureCallback.java +++ b/matrix-sdk/src/main/java/org/matrix/androidsdk/rest/callback/ApiFailureCallback.java @@ -1,12 +1,13 @@ -/* +/* * Copyright 2014 OpenMarket Ltd - * + * Copyright 2018 New Vector Ltd + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,7 +21,7 @@ /** * Callback interface for asynchronously returning API call failures. */ -public interface ApiFailureCallback { +public interface ApiFailureCallback extends ErrorCallback { /** * Called if there is a network error. @@ -36,10 +37,4 @@ public interface ApiFailureCallback { */ void onMatrixError(MatrixError e); - /** - * Called for some other type of error. - * - * @param e the exception - */ - void onUnexpectedError(Exception e); } diff --git a/matrix-sdk/src/main/java/org/matrix/androidsdk/rest/callback/ErrorCallback.java b/matrix-sdk/src/main/java/org/matrix/androidsdk/rest/callback/ErrorCallback.java new file mode 100644 index 000000000..fb178c870 --- /dev/null +++ b/matrix-sdk/src/main/java/org/matrix/androidsdk/rest/callback/ErrorCallback.java @@ -0,0 +1,30 @@ +/* + * Copyright 2018 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.matrix.androidsdk.rest.callback; + + +/** + * Callback interface for asynchronously returning API call failures. + */ +public interface ErrorCallback { + + /** + * Called for some other type of error. + * + * @param e the exception + */ + void onUnexpectedError(Exception e); +} diff --git a/matrix-sdk/src/main/java/org/matrix/androidsdk/rest/callback/SuccessErrorCallback.kt b/matrix-sdk/src/main/java/org/matrix/androidsdk/rest/callback/SuccessErrorCallback.kt new file mode 100644 index 000000000..a4377074b --- /dev/null +++ b/matrix-sdk/src/main/java/org/matrix/androidsdk/rest/callback/SuccessErrorCallback.kt @@ -0,0 +1,19 @@ +/* + * Copyright 2018 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.androidsdk.rest.callback + +interface SuccessErrorCallback : SuccessCallback, ErrorCallback