From a8641ef879904faf8f8de2c51bbea32c7b039522 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 3 Mar 2020 12:58:04 +0100 Subject: [PATCH 01/37] Split KeysBackup to several files. No other change. --- .../keysbackup/KeysBackupScenarioData.kt | 35 +++ .../crypto/keysbackup/KeysBackupTest.kt | 241 +++--------------- .../keysbackup/KeysBackupTestConstants.kt | 24 ++ .../crypto/keysbackup/KeysBackupTestHelper.kt | 182 +++++++++++++ .../keysbackup/PrepareKeysBackupDataResult.kt | 22 ++ 5 files changed, 296 insertions(+), 208 deletions(-) create mode 100644 matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupScenarioData.kt create mode 100644 matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestConstants.kt create mode 100644 matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestHelper.kt create mode 100644 matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/PrepareKeysBackupDataResult.kt diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupScenarioData.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupScenarioData.kt new file mode 100644 index 0000000000..f10f2fef0e --- /dev/null +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupScenarioData.kt @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2020 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 im.vector.matrix.android.internal.crypto.keysbackup + +import im.vector.matrix.android.api.session.Session +import im.vector.matrix.android.common.CommonTestHelper +import im.vector.matrix.android.common.CryptoTestData +import im.vector.matrix.android.internal.crypto.model.OlmInboundGroupSessionWrapper + +/** + * Data class to store result of [KeysBackupTestHelper.createKeysBackupScenarioWithPassword] + */ +data class KeysBackupScenarioData(val cryptoTestData: CryptoTestData, + val aliceKeys: List, + val prepareKeysBackupDataResult: PrepareKeysBackupDataResult, + val aliceSession2: Session) { + fun cleanUp(testHelper: CommonTestHelper) { + cryptoTestData.cleanUp(testHelper) + testHelper.signOutAndClose(aliceSession2) + } +} diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTest.kt index 3042a3c68f..59ef24beec 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTest.kt @@ -20,27 +20,19 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import im.vector.matrix.android.InstrumentedTest import im.vector.matrix.android.api.listeners.ProgressListener import im.vector.matrix.android.api.listeners.StepProgressListener -import im.vector.matrix.android.api.session.Session -import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupService import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupState import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupStateListener import im.vector.matrix.android.common.CommonTestHelper -import im.vector.matrix.android.common.CryptoTestData import im.vector.matrix.android.common.CryptoTestHelper -import im.vector.matrix.android.common.SessionTestParams import im.vector.matrix.android.common.TestConstants import im.vector.matrix.android.common.TestMatrixCallback -import im.vector.matrix.android.common.assertDictEquals -import im.vector.matrix.android.common.assertListEquals import im.vector.matrix.android.internal.crypto.MXCRYPTO_ALGORITHM_MEGOLM_BACKUP -import im.vector.matrix.android.internal.crypto.MegolmSessionData import im.vector.matrix.android.internal.crypto.crosssigning.DeviceTrustLevel import im.vector.matrix.android.internal.crypto.keysbackup.model.KeysBackupVersionTrust import im.vector.matrix.android.internal.crypto.keysbackup.model.MegolmBackupCreationInfo import im.vector.matrix.android.internal.crypto.keysbackup.model.rest.KeysVersion import im.vector.matrix.android.internal.crypto.keysbackup.model.rest.KeysVersionResult import im.vector.matrix.android.internal.crypto.model.ImportRoomKeysResult -import im.vector.matrix.android.internal.crypto.model.OlmInboundGroupSessionWrapper import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull @@ -61,9 +53,7 @@ class KeysBackupTest : InstrumentedTest { private val mTestHelper = CommonTestHelper(context()) private val mCryptoTestHelper = CryptoTestHelper(mTestHelper) - - private val defaultSessionParams = SessionTestParams(withInitialSync = false) - private val defaultSessionParamsWithInitialSync = SessionTestParams(withInitialSync = true) + private val mKeysBackupTestHelper = KeysBackupTestHelper(mTestHelper, mCryptoTestHelper) /** * - From doE2ETestWithAliceAndBobInARoomWithEncryptedMessages, we should have no backed up keys @@ -110,7 +100,7 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun prepareKeysBackupVersionTest() { - val bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams) + val bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) assertNotNull(bobSession.cryptoService().keysBackupService()) @@ -139,7 +129,7 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun createKeysBackupVersionTest() { - val bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams) + val bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) val keysBackup = bobSession.cryptoService().keysBackupService() @@ -182,7 +172,7 @@ class KeysBackupTest : InstrumentedTest { val stateObserver = StateObserver(keysBackup, latch, 5) - prepareAndCreateKeysBackupData(keysBackup) + mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) mTestHelper.await(latch) @@ -216,7 +206,7 @@ class KeysBackupTest : InstrumentedTest { val stateObserver = StateObserver(keysBackup) - prepareAndCreateKeysBackupData(keysBackup) + mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) // Check that backupAllGroupSessions returns valid data val nbOfKeys = cryptoTestData.firstSession.cryptoService().inboundGroupSessionsCount(false) @@ -263,7 +253,7 @@ class KeysBackupTest : InstrumentedTest { // - Pick a megolm key val session = keysBackup.store.inboundGroupSessionsToBackup(1)[0] - val keyBackupCreationInfo = prepareAndCreateKeysBackupData(keysBackup).megolmBackupCreationInfo + val keyBackupCreationInfo = mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup).megolmBackupCreationInfo // - Check encryptGroupSession() returns stg val keyBackupData = keysBackup.encryptGroupSession(session) @@ -281,7 +271,7 @@ class KeysBackupTest : InstrumentedTest { decryption!!) assertNotNull(sessionData) // - Compare the decrypted megolm key with the original one - assertKeysEquals(session.exportKeys(), sessionData) + mKeysBackupTestHelper.assertKeysEquals(session.exportKeys(), sessionData) stateObserver.stopAndCheckStates(null) cryptoTestData.cleanUp(mTestHelper) @@ -295,7 +285,7 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun restoreKeysBackupTest() { - val testData = createKeysBackupScenarioWithPassword(null) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(null) // - Restore the e2e backup from the homeserver val importRoomKeysResult = mTestHelper.doSync { @@ -308,7 +298,7 @@ class KeysBackupTest : InstrumentedTest { ) } - checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) + mKeysBackupTestHelper.checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) testData.cleanUp(mTestHelper) } @@ -329,7 +319,7 @@ class KeysBackupTest : InstrumentedTest { // fun restoreKeysBackupAndKeyShareRequestTest() { // fail("Check with Valere for this test. I think we do not send key share request") // -// val testData = createKeysBackupScenarioWithPassword(null) +// val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(null) // // // - Check the SDK sent key share requests // val cryptoStore2 = (testData.aliceSession2.cryptoService().keysBackupService() as DefaultKeysBackupService).store @@ -352,7 +342,7 @@ class KeysBackupTest : InstrumentedTest { // ) // } // -// checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) +// mKeysBackupTestHelper.checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) // // // - There must be no more pending key share requests // val unsentRequestAfterRestoration = cryptoStore2 @@ -380,7 +370,7 @@ class KeysBackupTest : InstrumentedTest { fun trustKeyBackupVersionTest() { // - Do an e2e backup to the homeserver with a recovery key // - And log Alice on a new device - val testData = createKeysBackupScenarioWithPassword(null) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(null) val stateObserver = StateObserver(testData.aliceSession2.cryptoService().keysBackupService()) @@ -399,7 +389,7 @@ class KeysBackupTest : InstrumentedTest { } // Wait for backup state to be ReadyToBackUp - waitForKeysBackupToBeInState(testData.aliceSession2, KeysBackupState.ReadyToBackUp) + mKeysBackupTestHelper.waitForKeysBackupToBeInState(testData.aliceSession2, KeysBackupState.ReadyToBackUp) // - Backup must be enabled on the new device, on the same version assertEquals(testData.prepareKeysBackupDataResult.version, testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion?.version) @@ -439,7 +429,7 @@ class KeysBackupTest : InstrumentedTest { fun trustKeyBackupVersionWithRecoveryKeyTest() { // - Do an e2e backup to the homeserver with a recovery key // - And log Alice on a new device - val testData = createKeysBackupScenarioWithPassword(null) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(null) val stateObserver = StateObserver(testData.aliceSession2.cryptoService().keysBackupService()) @@ -458,7 +448,7 @@ class KeysBackupTest : InstrumentedTest { } // Wait for backup state to be ReadyToBackUp - waitForKeysBackupToBeInState(testData.aliceSession2, KeysBackupState.ReadyToBackUp) + mKeysBackupTestHelper.waitForKeysBackupToBeInState(testData.aliceSession2, KeysBackupState.ReadyToBackUp) // - Backup must be enabled on the new device, on the same version assertEquals(testData.prepareKeysBackupDataResult.version, testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion?.version) @@ -496,7 +486,7 @@ class KeysBackupTest : InstrumentedTest { fun trustKeyBackupVersionWithWrongRecoveryKeyTest() { // - Do an e2e backup to the homeserver with a recovery key // - And log Alice on a new device - val testData = createKeysBackupScenarioWithPassword(null) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(null) val stateObserver = StateObserver(testData.aliceSession2.cryptoService().keysBackupService()) @@ -539,7 +529,7 @@ class KeysBackupTest : InstrumentedTest { // - Do an e2e backup to the homeserver with a password // - And log Alice on a new device - val testData = createKeysBackupScenarioWithPassword(password) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(password) val stateObserver = StateObserver(testData.aliceSession2.cryptoService().keysBackupService()) @@ -558,7 +548,7 @@ class KeysBackupTest : InstrumentedTest { } // Wait for backup state to be ReadyToBackUp - waitForKeysBackupToBeInState(testData.aliceSession2, KeysBackupState.ReadyToBackUp) + mKeysBackupTestHelper.waitForKeysBackupToBeInState(testData.aliceSession2, KeysBackupState.ReadyToBackUp) // - Backup must be enabled on the new device, on the same version assertEquals(testData.prepareKeysBackupDataResult.version, testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion?.version) @@ -599,7 +589,7 @@ class KeysBackupTest : InstrumentedTest { // - Do an e2e backup to the homeserver with a password // - And log Alice on a new device - val testData = createKeysBackupScenarioWithPassword(password) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(password) val stateObserver = StateObserver(testData.aliceSession2.cryptoService().keysBackupService()) @@ -634,7 +624,7 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun restoreKeysBackupWithAWrongRecoveryKeyTest() { - val testData = createKeysBackupScenarioWithPassword(null) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(null) // - Try to restore the e2e backup with a wrong recovery key val latch2 = CountDownLatch(1) @@ -669,7 +659,7 @@ class KeysBackupTest : InstrumentedTest { fun testBackupWithPassword() { val password = "password" - val testData = createKeysBackupScenarioWithPassword(password) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(password) // - Restore the e2e backup with the password val steps = ArrayList() @@ -709,7 +699,7 @@ class KeysBackupTest : InstrumentedTest { assertEquals(50, (steps[103] as StepProgressListener.Step.ImportingKey).progress) assertEquals(100, (steps[104] as StepProgressListener.Step.ImportingKey).progress) - checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) + mKeysBackupTestHelper.checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) testData.cleanUp(mTestHelper) } @@ -725,7 +715,7 @@ class KeysBackupTest : InstrumentedTest { val password = "password" val wrongPassword = "passw0rd" - val testData = createKeysBackupScenarioWithPassword(password) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(password) // - Try to restore the e2e backup with a wrong password val latch2 = CountDownLatch(1) @@ -760,7 +750,7 @@ class KeysBackupTest : InstrumentedTest { fun testUseRecoveryKeyToRestoreAPasswordBasedKeysBackup() { val password = "password" - val testData = createKeysBackupScenarioWithPassword(password) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(password) // - Restore the e2e backup with the recovery key. val importRoomKeysResult = mTestHelper.doSync { @@ -773,7 +763,7 @@ class KeysBackupTest : InstrumentedTest { ) } - checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) + mKeysBackupTestHelper.checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) testData.cleanUp(mTestHelper) } @@ -786,7 +776,7 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun testUsePasswordToRestoreARecoveryKeyBasedKeysBackup() { - val testData = createKeysBackupScenarioWithPassword(null) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(null) // - Try to restore the e2e backup with a password val latch2 = CountDownLatch(1) @@ -825,7 +815,7 @@ class KeysBackupTest : InstrumentedTest { val stateObserver = StateObserver(keysBackup) // - Do an e2e backup to the homeserver - prepareAndCreateKeysBackupData(keysBackup) + mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) // Get key backup version from the home server val keysVersionResult = mTestHelper.doSync { @@ -870,13 +860,13 @@ class KeysBackupTest : InstrumentedTest { assertFalse(keysBackup.isEnabled) - val keyBackupCreationInfo = prepareAndCreateKeysBackupData(keysBackup) + val keyBackupCreationInfo = mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) assertTrue(keysBackup.isEnabled) // - Restart alice session // - Log Alice on a new device - val aliceSession2 = mTestHelper.logIntoAccount(cryptoTestData.firstSession.myUserId, defaultSessionParamsWithInitialSync) + val aliceSession2 = mTestHelper.logIntoAccount(cryptoTestData.firstSession.myUserId, KeysBackupTestConstants.defaultSessionParamsWithInitialSync) cryptoTestData.cleanUp(mTestHelper) @@ -950,7 +940,7 @@ class KeysBackupTest : InstrumentedTest { }) // - Make alice back up her keys to her homeserver - prepareAndCreateKeysBackupData(keysBackup) + mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) assertTrue(keysBackup.isEnabled) @@ -1000,7 +990,7 @@ class KeysBackupTest : InstrumentedTest { val stateObserver = StateObserver(keysBackup) // - Make alice back up her keys to her homeserver - prepareAndCreateKeysBackupData(keysBackup) + mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) // Wait for keys backup to finish by asking again to backup keys. mTestHelper.doSync { @@ -1012,7 +1002,7 @@ class KeysBackupTest : InstrumentedTest { val aliceUserId = cryptoTestData.firstSession.myUserId // - Log Alice on a new device - val aliceSession2 = mTestHelper.logIntoAccount(aliceUserId, defaultSessionParamsWithInitialSync) + val aliceSession2 = mTestHelper.logIntoAccount(aliceUserId, KeysBackupTestConstants.defaultSessionParamsWithInitialSync) // - Post a message to have a new megolm session aliceSession2.cryptoService().setWarnOnUnknownDevices(false) @@ -1093,7 +1083,7 @@ class KeysBackupTest : InstrumentedTest { assertFalse(keysBackup.isEnabled) - val keyBackupCreationInfo = prepareAndCreateKeysBackupData(keysBackup) + val keyBackupCreationInfo = mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) assertTrue(keysBackup.isEnabled) @@ -1106,169 +1096,4 @@ class KeysBackupTest : InstrumentedTest { stateObserver.stopAndCheckStates(null) cryptoTestData.cleanUp(mTestHelper) } - - /* ========================================================================================== - * Private - * ========================================================================================== */ - - /** - * As KeysBackup is doing asynchronous call to update its internal state, this method help to wait for the - * KeysBackup object to be in the specified state - */ - private fun waitForKeysBackupToBeInState(session: Session, state: KeysBackupState) { - // If already in the wanted state, return - if (session.cryptoService().keysBackupService().state == state) { - return - } - - // Else observe state changes - val latch = CountDownLatch(1) - - session.cryptoService().keysBackupService().addListener(object : KeysBackupStateListener { - override fun onStateChange(newState: KeysBackupState) { - if (newState == state) { - session.cryptoService().keysBackupService().removeListener(this) - latch.countDown() - } - } - }) - - mTestHelper.await(latch) - } - - private data class PrepareKeysBackupDataResult(val megolmBackupCreationInfo: MegolmBackupCreationInfo, - val version: String) - - private fun prepareAndCreateKeysBackupData(keysBackup: KeysBackupService, - password: String? = null): PrepareKeysBackupDataResult { - val stateObserver = StateObserver(keysBackup) - - val megolmBackupCreationInfo = mTestHelper.doSync { - keysBackup.prepareKeysBackupVersion(password, null, it) - } - - assertNotNull(megolmBackupCreationInfo) - - assertFalse(keysBackup.isEnabled) - - // Create the version - val keysVersion = mTestHelper.doSync { - keysBackup.createKeysBackupVersion(megolmBackupCreationInfo, it) - } - - assertNotNull(keysVersion.version) - - // Backup must be enable now - assertTrue(keysBackup.isEnabled) - - stateObserver.stopAndCheckStates(null) - return PrepareKeysBackupDataResult(megolmBackupCreationInfo, keysVersion.version!!) - } - - private fun assertKeysEquals(keys1: MegolmSessionData?, keys2: MegolmSessionData?) { - assertNotNull(keys1) - assertNotNull(keys2) - - assertEquals(keys1?.algorithm, keys2?.algorithm) - assertEquals(keys1?.roomId, keys2?.roomId) - // No need to compare the shortcut - // assertEquals(keys1?.sender_claimed_ed25519_key, keys2?.sender_claimed_ed25519_key) - assertEquals(keys1?.senderKey, keys2?.senderKey) - assertEquals(keys1?.sessionId, keys2?.sessionId) - assertEquals(keys1?.sessionKey, keys2?.sessionKey) - - assertListEquals(keys1?.forwardingCurve25519KeyChain, keys2?.forwardingCurve25519KeyChain) - assertDictEquals(keys1?.senderClaimedKeys, keys2?.senderClaimedKeys) - } - - /** - * Data class to store result of [createKeysBackupScenarioWithPassword] - */ - private data class KeysBackupScenarioData(val cryptoTestData: CryptoTestData, - val aliceKeys: List, - val prepareKeysBackupDataResult: PrepareKeysBackupDataResult, - val aliceSession2: Session) { - fun cleanUp(testHelper: CommonTestHelper) { - cryptoTestData.cleanUp(testHelper) - testHelper.signOutAndClose(aliceSession2) - } - } - - /** - * Common initial condition - * - Do an e2e backup to the homeserver - * - Log Alice on a new device, and wait for its keysBackup object to be ready (in state NotTrusted) - * - * @param password optional password - */ - private fun createKeysBackupScenarioWithPassword(password: String?): KeysBackupScenarioData { - val cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() - - val cryptoStore = (cryptoTestData.firstSession.cryptoService().keysBackupService() as DefaultKeysBackupService).store - val keysBackup = cryptoTestData.firstSession.cryptoService().keysBackupService() - - val stateObserver = StateObserver(keysBackup) - - val aliceKeys = cryptoStore.inboundGroupSessionsToBackup(100) - - // - Do an e2e backup to the homeserver - val prepareKeysBackupDataResult = prepareAndCreateKeysBackupData(keysBackup, password) - - var lastProgress = 0 - var lastTotal = 0 - mTestHelper.doSync { - keysBackup.backupAllGroupSessions(object : ProgressListener { - override fun onProgress(progress: Int, total: Int) { - lastProgress = progress - lastTotal = total - } - }, it) - } - - assertEquals(2, lastProgress) - assertEquals(2, lastTotal) - - val aliceUserId = cryptoTestData.firstSession.myUserId - - // - Log Alice on a new device - val aliceSession2 = mTestHelper.logIntoAccount(aliceUserId, defaultSessionParamsWithInitialSync) - - // Test check: aliceSession2 has no keys at login - assertEquals(0, aliceSession2.cryptoService().inboundGroupSessionsCount(false)) - - // Wait for backup state to be NotTrusted - waitForKeysBackupToBeInState(aliceSession2, KeysBackupState.NotTrusted) - - stateObserver.stopAndCheckStates(null) - - return KeysBackupScenarioData(cryptoTestData, - aliceKeys, - prepareKeysBackupDataResult, - aliceSession2) - } - - /** - * Common restore success check after [createKeysBackupScenarioWithPassword]: - * - Imported keys number must be correct - * - The new device must have the same count of megolm keys - * - Alice must have the same keys on both devices - */ - private fun checkRestoreSuccess(testData: KeysBackupScenarioData, - total: Int, - imported: Int) { - // - Imported keys number must be correct - assertEquals(testData.aliceKeys.size, total) - assertEquals(total, imported) - - // - The new device must have the same count of megolm keys - assertEquals(testData.aliceKeys.size, testData.aliceSession2.cryptoService().inboundGroupSessionsCount(false)) - - // - Alice must have the same keys on both devices - for (aliceKey1 in testData.aliceKeys) { - val aliceKey2 = (testData.aliceSession2.cryptoService().keysBackupService() as DefaultKeysBackupService).store - .getInboundGroupSession(aliceKey1.olmInboundGroupSession!!.sessionIdentifier(), aliceKey1.senderKey!!) - assertNotNull(aliceKey2) - assertKeysEquals(aliceKey1.exportKeys(), aliceKey2!!.exportKeys()) - } - } } diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestConstants.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestConstants.kt new file mode 100644 index 0000000000..0f3a23df3f --- /dev/null +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestConstants.kt @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2020 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 im.vector.matrix.android.internal.crypto.keysbackup + +import im.vector.matrix.android.common.SessionTestParams + +object KeysBackupTestConstants { + val defaultSessionParams = SessionTestParams(withInitialSync = false) + val defaultSessionParamsWithInitialSync = SessionTestParams(withInitialSync = true) +} diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestHelper.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestHelper.kt new file mode 100644 index 0000000000..bb1436b8d4 --- /dev/null +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestHelper.kt @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2020 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 im.vector.matrix.android.internal.crypto.keysbackup + +import im.vector.matrix.android.api.listeners.ProgressListener +import im.vector.matrix.android.api.session.Session +import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupService +import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupState +import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupStateListener +import im.vector.matrix.android.common.CommonTestHelper +import im.vector.matrix.android.common.CryptoTestHelper +import im.vector.matrix.android.common.assertDictEquals +import im.vector.matrix.android.common.assertListEquals +import im.vector.matrix.android.internal.crypto.MegolmSessionData +import im.vector.matrix.android.internal.crypto.keysbackup.model.MegolmBackupCreationInfo +import im.vector.matrix.android.internal.crypto.keysbackup.model.rest.KeysVersion +import org.junit.Assert +import java.util.concurrent.CountDownLatch + +class KeysBackupTestHelper( + private val mTestHelper: CommonTestHelper, + private val mCryptoTestHelper: CryptoTestHelper) { + + /** + * Common initial condition + * - Do an e2e backup to the homeserver + * - Log Alice on a new device, and wait for its keysBackup object to be ready (in state NotTrusted) + * + * @param password optional password + */ + fun createKeysBackupScenarioWithPassword(password: String?): KeysBackupScenarioData { + val cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() + + val cryptoStore = (cryptoTestData.firstSession.cryptoService().keysBackupService() as DefaultKeysBackupService).store + val keysBackup = cryptoTestData.firstSession.cryptoService().keysBackupService() + + val stateObserver = StateObserver(keysBackup) + + val aliceKeys = cryptoStore.inboundGroupSessionsToBackup(100) + + // - Do an e2e backup to the homeserver + val prepareKeysBackupDataResult = prepareAndCreateKeysBackupData(keysBackup, password) + + var lastProgress = 0 + var lastTotal = 0 + mTestHelper.doSync { + keysBackup.backupAllGroupSessions(object : ProgressListener { + override fun onProgress(progress: Int, total: Int) { + lastProgress = progress + lastTotal = total + } + }, it) + } + + Assert.assertEquals(2, lastProgress) + Assert.assertEquals(2, lastTotal) + + val aliceUserId = cryptoTestData.firstSession.myUserId + + // - Log Alice on a new device + val aliceSession2 = mTestHelper.logIntoAccount(aliceUserId, KeysBackupTestConstants.defaultSessionParamsWithInitialSync) + + // Test check: aliceSession2 has no keys at login + Assert.assertEquals(0, aliceSession2.cryptoService().inboundGroupSessionsCount(false)) + + // Wait for backup state to be NotTrusted + waitForKeysBackupToBeInState(aliceSession2, KeysBackupState.NotTrusted) + + stateObserver.stopAndCheckStates(null) + + return KeysBackupScenarioData(cryptoTestData, + aliceKeys, + prepareKeysBackupDataResult, + aliceSession2) + } + + fun prepareAndCreateKeysBackupData(keysBackup: KeysBackupService, + password: String? = null): PrepareKeysBackupDataResult { + val stateObserver = StateObserver(keysBackup) + + val megolmBackupCreationInfo = mTestHelper.doSync { + keysBackup.prepareKeysBackupVersion(password, null, it) + } + + Assert.assertNotNull(megolmBackupCreationInfo) + + Assert.assertFalse(keysBackup.isEnabled) + + // Create the version + val keysVersion = mTestHelper.doSync { + keysBackup.createKeysBackupVersion(megolmBackupCreationInfo, it) + } + + Assert.assertNotNull(keysVersion.version) + + // Backup must be enable now + Assert.assertTrue(keysBackup.isEnabled) + + stateObserver.stopAndCheckStates(null) + return PrepareKeysBackupDataResult(megolmBackupCreationInfo, keysVersion.version!!) + } + + /** + * As KeysBackup is doing asynchronous call to update its internal state, this method help to wait for the + * KeysBackup object to be in the specified state + */ + fun waitForKeysBackupToBeInState(session: Session, state: KeysBackupState) { + // If already in the wanted state, return + if (session.cryptoService().keysBackupService().state == state) { + return + } + + // Else observe state changes + val latch = CountDownLatch(1) + + session.cryptoService().keysBackupService().addListener(object : KeysBackupStateListener { + override fun onStateChange(newState: KeysBackupState) { + if (newState == state) { + session.cryptoService().keysBackupService().removeListener(this) + latch.countDown() + } + } + }) + + mTestHelper.await(latch) + } + + fun assertKeysEquals(keys1: MegolmSessionData?, keys2: MegolmSessionData?) { + Assert.assertNotNull(keys1) + Assert.assertNotNull(keys2) + + Assert.assertEquals(keys1?.algorithm, keys2?.algorithm) + Assert.assertEquals(keys1?.roomId, keys2?.roomId) + // No need to compare the shortcut + // assertEquals(keys1?.sender_claimed_ed25519_key, keys2?.sender_claimed_ed25519_key) + Assert.assertEquals(keys1?.senderKey, keys2?.senderKey) + Assert.assertEquals(keys1?.sessionId, keys2?.sessionId) + Assert.assertEquals(keys1?.sessionKey, keys2?.sessionKey) + + assertListEquals(keys1?.forwardingCurve25519KeyChain, keys2?.forwardingCurve25519KeyChain) + assertDictEquals(keys1?.senderClaimedKeys, keys2?.senderClaimedKeys) + } + + /** + * Common restore success check after [KeysBackupTestHelper.createKeysBackupScenarioWithPassword]: + * - Imported keys number must be correct + * - The new device must have the same count of megolm keys + * - Alice must have the same keys on both devices + */ + fun checkRestoreSuccess(testData: KeysBackupScenarioData, + total: Int, + imported: Int) { + // - Imported keys number must be correct + Assert.assertEquals(testData.aliceKeys.size, total) + Assert.assertEquals(total, imported) + + // - The new device must have the same count of megolm keys + Assert.assertEquals(testData.aliceKeys.size, testData.aliceSession2.cryptoService().inboundGroupSessionsCount(false)) + + // - Alice must have the same keys on both devices + for (aliceKey1 in testData.aliceKeys) { + val aliceKey2 = (testData.aliceSession2.cryptoService().keysBackupService() as DefaultKeysBackupService).store + .getInboundGroupSession(aliceKey1.olmInboundGroupSession!!.sessionIdentifier(), aliceKey1.senderKey!!) + Assert.assertNotNull(aliceKey2) + assertKeysEquals(aliceKey1.exportKeys(), aliceKey2!!.exportKeys()) + } + } +} diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/PrepareKeysBackupDataResult.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/PrepareKeysBackupDataResult.kt new file mode 100644 index 0000000000..91d00cbe21 --- /dev/null +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/PrepareKeysBackupDataResult.kt @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2020 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 im.vector.matrix.android.internal.crypto.keysbackup + +import im.vector.matrix.android.internal.crypto.keysbackup.model.MegolmBackupCreationInfo + +data class PrepareKeysBackupDataResult(val megolmBackupCreationInfo: MegolmBackupCreationInfo, + val version: String) From 41a8f4024198cba55e93fd297bed406aac1b6509 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 3 Mar 2020 18:22:44 +0100 Subject: [PATCH 02/37] Improve API --- .../matrix/android/api/session/room/timeline/Timeline.kt | 1 + .../matrix/android/internal/crypto/store/IMXCryptoStore.kt | 2 +- .../android/internal/crypto/store/db/RealmCryptoStore.kt | 6 +----- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/room/timeline/Timeline.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/room/timeline/Timeline.kt index eb4a9b59e4..d7d6682046 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/room/timeline/Timeline.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/room/timeline/Timeline.kt @@ -104,6 +104,7 @@ interface Timeline { interface Listener { /** * Call when the timeline has been updated through pagination or sync. + * The latest event is the first in the list * @param snapshot the most up to date snapshot */ fun onTimelineUpdated(snapshot: List) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt index a8f65e9219..c5a89b10e7 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt @@ -262,7 +262,7 @@ internal interface IMXCryptoStore { * @param deviceKey the public key of the other device. * @return The Base64 end-to-end session, or null if not found */ - fun getDeviceSession(sessionId: String?, deviceKey: String?): OlmSessionWrapper? + fun getDeviceSession(sessionId: String, deviceKey: String): OlmSessionWrapper? /** * Retrieve the last used sessionId, regarding `lastReceivedMessageTs`, or null if no session exist diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/db/RealmCryptoStore.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/db/RealmCryptoStore.kt index bd51cf8539..a6f3f5d593 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/db/RealmCryptoStore.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/db/RealmCryptoStore.kt @@ -555,11 +555,7 @@ internal class RealmCryptoStore @Inject constructor( } } - override fun getDeviceSession(sessionId: String?, deviceKey: String?): OlmSessionWrapper? { - if (sessionId == null || deviceKey == null) { - return null - } - + override fun getDeviceSession(sessionId: String, deviceKey: String): OlmSessionWrapper? { val key = OlmSessionEntity.createPrimaryKey(sessionId, deviceKey) // If not in cache (or not found), try to read it from realm From 0cb43eef51786867f855f5e4c8c9c1f4118664e5 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 3 Mar 2020 18:23:31 +0100 Subject: [PATCH 03/37] Add test for Unwedging (before implementing it) --- .idea/dictionaries/bmarty.xml | 1 + .../matrix/android/common/CryptoTestHelper.kt | 66 ++----- .../android/internal/crypto/UnwedgingTest.kt | 174 ++++++++++++++++++ .../internal/crypto/DefaultCryptoService.kt | 8 + 4 files changed, 203 insertions(+), 46 deletions(-) create mode 100644 matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt diff --git a/.idea/dictionaries/bmarty.xml b/.idea/dictionaries/bmarty.xml index 7e9a9e1b03..1f93d1feee 100644 --- a/.idea/dictionaries/bmarty.xml +++ b/.idea/dictionaries/bmarty.xml @@ -25,6 +25,7 @@ signup ssss threepid + unwedging \ No newline at end of file diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt index 826c70a63f..1084dc423d 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt @@ -22,6 +22,7 @@ import im.vector.matrix.android.api.session.Session import im.vector.matrix.android.api.session.events.model.Event import im.vector.matrix.android.api.session.events.model.EventType import im.vector.matrix.android.api.session.events.model.toContent +import im.vector.matrix.android.api.session.room.Room import im.vector.matrix.android.api.session.room.model.Membership import im.vector.matrix.android.api.session.room.model.RoomSummary import im.vector.matrix.android.api.session.room.model.create.CreateRoomParams @@ -40,7 +41,6 @@ import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull -import org.junit.Assert.assertTrue import java.util.HashMap import java.util.concurrent.CountDownLatch @@ -140,64 +140,38 @@ class CryptoTestHelper(private val mTestHelper: CommonTestHelper) { * @return Alice, Bob and Sam session */ fun doE2ETestWithAliceAndBobAndSamInARoom(): CryptoTestData { - val statuses = HashMap() - val cryptoTestData = doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession val aliceRoomId = cryptoTestData.roomId val room = aliceSession.getRoom(aliceRoomId)!! - val samSession = mTestHelper.createAccount(TestConstants.USER_SAM, defaultSessionParams) - - 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, null, object : TestMatrixCallback(lock1) { - override fun onSuccess(data: Unit) { - statuses["invite"] = "invite" - super.onSuccess(data) - } - }) - - mTestHelper.await(lock1) - - assertTrue(statuses.containsKey("invite") && statuses.containsKey("onNewRoom")) - -// samSession.dataHandler.removeListener(samEventListener) - - val lock2 = CountDownLatch(1) - - samSession.joinRoom(aliceRoomId, null, object : TestMatrixCallback(lock2) { - override fun onSuccess(data: Unit) { - statuses["joinRoom"] = "joinRoom" - super.onSuccess(data) - } - }) - - mTestHelper.await(lock2) - assertTrue(statuses.containsKey("joinRoom")) + val samSession = createSamAccountAndInviteToTheRoom(room) // wait the initial sync SystemClock.sleep(1000) -// samSession.dataHandler.removeListener(samEventListener) - return CryptoTestData(aliceSession, aliceRoomId, cryptoTestData.secondSession, samSession) } + /** + * Create Sam account and invite him in the room. He will accept the invitation + * @Return Sam session + */ + fun createSamAccountAndInviteToTheRoom(room: Room): Session { + val samSession = mTestHelper.createAccount(TestConstants.USER_SAM, defaultSessionParams) + + mTestHelper.doSync { + room.invite(samSession.myUserId, null, it) + } + + mTestHelper.doSync { + samSession.joinRoom(room.roomId, null, it) + } + + return samSession + } + /** * @return Alice and Bob sessions */ diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt new file mode 100644 index 0000000000..ce5873b451 --- /dev/null +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2020 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 im.vector.matrix.android.internal.crypto + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import im.vector.matrix.android.InstrumentedTest +import im.vector.matrix.android.api.session.events.model.EventType +import im.vector.matrix.android.api.session.room.timeline.Timeline +import im.vector.matrix.android.api.session.room.timeline.TimelineEvent +import im.vector.matrix.android.api.session.room.timeline.TimelineSettings +import im.vector.matrix.android.common.CommonTestHelper +import im.vector.matrix.android.common.CryptoTestHelper +import org.amshove.kluent.shouldBe +import org.amshove.kluent.shouldBeEqualTo +import org.junit.Before +import org.junit.FixMethodOrder +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.MethodSorters +import java.util.concurrent.CountDownLatch + +/** + * Ref: + * - https://github.com/matrix-org/matrix-doc/pull/1719 + * - https://matrix.org/docs/spec/client_server/latest#recovering-from-undecryptable-messages + * - https://github.com/matrix-org/matrix-js-sdk/pull/780 + * - https://github.com/matrix-org/matrix-ios-sdk/pull/778 + * - https://github.com/matrix-org/matrix-ios-sdk/pull/784 + */ +@RunWith(AndroidJUnit4::class) +@FixMethodOrder(MethodSorters.JVM) +class UnwedgingTest : InstrumentedTest { + + private lateinit var messagesReceivedByBob: List + private val mTestHelper = CommonTestHelper(context()) + private val mCryptoTestHelper = CryptoTestHelper(mTestHelper) + + @Before + fun init() { + messagesReceivedByBob = emptyList() + } + + /** + * - Alice & Bob in a e2e room + * - Alice sends a 1st message with a 1st megolm session + * - Store the olm session between A&B devices + * - Alice sends a 2nd message with a 2nd megolm session + * - Simulate Alice using a backup of her OS and make her crypto state like after the first message + * - Alice sends a 3rd message with a 3rd megolm session but a wedged olm session + * + * What Bob must see: + * -> No issue with the 2 first messages + * -> The third event must fail to decrypt at first because Bob the olm session is wedged + * -> This is automatically fixed after SDKs restarted the olm session + */ + @Test + fun testUnwedging() { + val cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom() + + val aliceSession = cryptoTestData.firstSession + val aliceRoomId = cryptoTestData.roomId + val bobSession = cryptoTestData.secondSession!! + + val aliceCryptoStore = (aliceSession.cryptoService() as DefaultCryptoService).cryptoStoreForTesting + + bobSession.cryptoService().setWarnOnUnknownDevices(false) + + aliceSession.cryptoService().setWarnOnUnknownDevices(false) + + val roomFromBobPOV = bobSession.getRoom(aliceRoomId)!! + val roomFromAlicePOV = aliceSession.getRoom(aliceRoomId)!! + + val bobTimeline = roomFromBobPOV.createTimeline(null, TimelineSettings(20)) + bobTimeline.start() + + var latch = CountDownLatch(1) + var bobEventsListener = createEventListener(latch, 1) + bobTimeline.addListener(bobEventsListener) + messagesReceivedByBob = emptyList() + + // - Alice sends a 1st message with a 1st megolm session + roomFromAlicePOV.sendTextMessage("First message") + + // Wait for the message to be received by Bob + mTestHelper.await(latch) + bobTimeline.removeListener(bobEventsListener) + + messagesReceivedByBob.size shouldBe 1 + + // - Store the olm session between A&B devices + // Let us pickle our session with bob here so we can later unpickle it + // and wedge our session. + val sessionIdsForBob = aliceCryptoStore.getDeviceSessionIds(bobSession.cryptoService().getMyDevice().identityKey()!!) + sessionIdsForBob!!.size shouldBe 1 + val olmSession = aliceCryptoStore.getDeviceSession(sessionIdsForBob.first(), bobSession.cryptoService().getMyDevice().identityKey()!!)!! + + // Sam join the room + val samSession = mCryptoTestHelper.createSamAccountAndInviteToTheRoom(roomFromAlicePOV) + + latch = CountDownLatch(1) + bobEventsListener = createEventListener(latch, 2) + bobTimeline.addListener(bobEventsListener) + messagesReceivedByBob = emptyList() + + // - Alice sends a 2nd message with a 2nd megolm session + roomFromAlicePOV.sendTextMessage("Second message") + + // Wait for the message to be received by Bob + mTestHelper.await(latch) + bobTimeline.removeListener(bobEventsListener) + + messagesReceivedByBob.size shouldBe 2 + + // Let us wedge the session now. Set crypto state like after the first message + aliceCryptoStore.storeSession(olmSession, bobSession.cryptoService().getMyDevice().identityKey()!!) + + latch = CountDownLatch(1) + bobEventsListener = createEventListener(latch, 3) + bobTimeline.addListener(bobEventsListener) + messagesReceivedByBob = emptyList() + + // - Alice sends a 3rd message with a 3rd megolm session but a wedged olm session + roomFromAlicePOV.sendTextMessage("Third message") + + // Wait for the message to be received by Bob + mTestHelper.await(latch) + bobTimeline.removeListener(bobEventsListener) + + messagesReceivedByBob.size shouldBe 3 + + messagesReceivedByBob[0].root.getClearType() shouldBeEqualTo EventType.ENCRYPTED + messagesReceivedByBob[1].root.getClearType() shouldBeEqualTo EventType.MESSAGE + messagesReceivedByBob[2].root.getClearType() shouldBeEqualTo EventType.MESSAGE + + bobTimeline.dispose() + + cryptoTestData.cleanUp(mTestHelper) + mTestHelper.signOutAndClose(samSession) + } + + private fun createEventListener(latch: CountDownLatch, expectedNumberOfMessages: Int): Timeline.Listener { + return object : Timeline.Listener { + override fun onTimelineFailure(throwable: Throwable) { + // noop + } + + override fun onNewTimelineEvents(eventIds: List) { + // noop + } + + override fun onTimelineUpdated(snapshot: List) { + messagesReceivedByBob = snapshot.filter { it.root.type == EventType.ENCRYPTED } + + if (messagesReceivedByBob.size == expectedNumberOfMessages) { + latch.countDown() + } + } + } + } +} diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt index aceead8ea0..61a072ece6 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt @@ -21,6 +21,7 @@ package im.vector.matrix.android.internal.crypto import android.content.Context import android.os.Handler import android.os.Looper +import androidx.annotation.VisibleForTesting import androidx.lifecycle.LiveData import com.squareup.moshi.Types import com.zhuinden.monarchy.Monarchy @@ -1192,4 +1193,11 @@ internal class DefaultCryptoService @Inject constructor( override fun getGossipingEventsTrail(): List { return cryptoStore.getGossipingEventsTrail() } + + /* ========================================================================================== + * For test only + * ========================================================================================== */ + + @VisibleForTesting + val cryptoStoreForTesting = cryptoStore } From 00c239bc4212e06133cf3537ee6c2b0c572b75f9 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Wed, 4 Mar 2020 12:15:13 +0100 Subject: [PATCH 04/37] cleanup --- .../java/im/vector/matrix/android/common/CryptoTestHelper.kt | 1 - .../matrix/android/internal/crypto/store/IMXCryptoStore.kt | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt index 1084dc423d..9278bed918 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt @@ -41,7 +41,6 @@ import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull -import java.util.HashMap import java.util.concurrent.CountDownLatch class CryptoTestHelper(private val mTestHelper: CommonTestHelper) { diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt index c5a89b10e7..0d1026b69f 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt @@ -196,7 +196,8 @@ internal interface IMXCryptoStore { */ fun storeUserDevices(userId: String, devices: Map?) - fun storeUserCrossSigningKeys(userId: String, masterKey: CryptoCrossSigningKey?, + fun storeUserCrossSigningKeys(userId: String, + masterKey: CryptoCrossSigningKey?, selfSigningKey: CryptoCrossSigningKey?, userSigningKey: CryptoCrossSigningKey?) From 590024501875723c1a988cbeaa6c67e6baa73eab Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 10 Mar 2020 11:42:02 +0100 Subject: [PATCH 05/37] Make the test fail before unwedging implementation --- .../android/internal/crypto/UnwedgingTest.kt | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt index ce5873b451..4a28a77986 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt @@ -87,6 +87,26 @@ class UnwedgingTest : InstrumentedTest { val bobTimeline = roomFromBobPOV.createTimeline(null, TimelineSettings(20)) bobTimeline.start() + val bobFinalLatch = CountDownLatch(1) + val bobHasThreeDecryptedEventsListener = object : Timeline.Listener { + override fun onTimelineFailure(throwable: Throwable) { + // noop + } + + override fun onNewTimelineEvents(eventIds: List) { + // noop + } + + override fun onTimelineUpdated(snapshot: List) { + val decryptedEventReceivedByBob = snapshot.filter { it.root.getClearType() == EventType.MESSAGE } + if (decryptedEventReceivedByBob.size == 3) { + bobFinalLatch.countDown() + } + } + } + bobTimeline.addListener(bobHasThreeDecryptedEventsListener) + + var latch = CountDownLatch(1) var bobEventsListener = createEventListener(latch, 1) bobTimeline.addListener(bobEventsListener) @@ -146,6 +166,10 @@ class UnwedgingTest : InstrumentedTest { messagesReceivedByBob[1].root.getClearType() shouldBeEqualTo EventType.MESSAGE messagesReceivedByBob[2].root.getClearType() shouldBeEqualTo EventType.MESSAGE + // Wait for all the message to be decrypted by bob + mTestHelper.await(bobFinalLatch) + bobTimeline.removeListener(bobHasThreeDecryptedEventsListener) + bobTimeline.dispose() cryptoTestData.cleanUp(mTestHelper) From 7924ef207c19985f6a54c9357ca2c1b36d8fcb38 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 10 Mar 2020 16:00:31 +0100 Subject: [PATCH 06/37] Add Javadoc --- .../model/rest/ForwardedRoomKeyContent.kt | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/ForwardedRoomKeyContent.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/ForwardedRoomKeyContent.kt index cf8652352c..ea5fb26d83 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/ForwardedRoomKeyContent.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/ForwardedRoomKeyContent.kt @@ -20,28 +20,53 @@ import com.squareup.moshi.JsonClass /** * Class representing the forward room key request body content + * Ref: https://matrix.org/docs/spec/client_server/latest#m-forwarded-room-key */ @JsonClass(generateAdapter = true) data class ForwardedRoomKeyContent( - + /** + * Required. The encryption algorithm the key in this event is to be used with. + */ @Json(name = "algorithm") val algorithm: String? = null, + /** + * Required. The room where the key is used. + */ @Json(name = "room_id") val roomId: String? = null, + /** + * Required. The Curve25519 key of the device which initiated the session originally. + */ @Json(name = "sender_key") val senderKey: String? = null, + /** + * Required. The ID of the session that the key is for. + */ @Json(name = "session_id") val sessionId: String? = null, + /** + * Required. The key to be exchanged. + */ @Json(name = "session_key") val sessionKey: String? = null, + /** + * Required. Chain of Curve25519 keys. It starts out empty, but each time the key is forwarded to another device, + * the previous sender in the chain is added to the end of the list. For example, if the key is forwarded + * from A to B to C, this field is empty between A and B, and contains A's Curve25519 key between B and C. + */ @Json(name = "forwarding_curve25519_key_chain") val forwardingCurve25519KeyChain: List? = null, + /** + * Required. The Ed25519 key of the device which initiated the session originally. It is 'claimed' because the + * receiving device has no way to tell that the original room_key actually came from a device which owns the + * private part of this key unless they have done device verification. + */ @Json(name = "sender_claimed_ed25519_key") val senderClaimedEd25519Key: String? = null ) From a42eb421783f25651463be1b9c8326a1ccc334a6 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 10 Mar 2020 16:13:46 +0100 Subject: [PATCH 07/37] Avoid injecting Credentials --- .../crypto/actions/MessageEncrypter.kt | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt index fae205e581..9961f40b9a 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt @@ -16,19 +16,24 @@ package im.vector.matrix.android.internal.crypto.actions -import im.vector.matrix.android.api.auth.data.Credentials +import im.vector.matrix.android.api.session.events.model.Content import im.vector.matrix.android.internal.crypto.MXCRYPTO_ALGORITHM_OLM import im.vector.matrix.android.internal.crypto.MXOlmDevice import im.vector.matrix.android.internal.crypto.model.CryptoDeviceInfo import im.vector.matrix.android.internal.crypto.model.rest.EncryptedMessage +import im.vector.matrix.android.internal.di.DeviceId +import im.vector.matrix.android.internal.di.UserId import im.vector.matrix.android.internal.util.JsonCanonicalizer import im.vector.matrix.android.internal.util.convertToUTF8 import timber.log.Timber import javax.inject.Inject -internal class MessageEncrypter @Inject constructor(private val credentials: Credentials, - private val olmDevice: MXOlmDevice) { - +internal class MessageEncrypter @Inject constructor( + @UserId + private val userId: String, + @DeviceId + private val deviceId: String?, + private val olmDevice: MXOlmDevice) { /** * Encrypt an event payload for a list of devices. * This method must be called from the getCryptoHandler() thread. @@ -37,13 +42,13 @@ internal class MessageEncrypter @Inject constructor(private val credentials: Cre * @param deviceInfos list of device infos to encrypt for. * @return the content for an m.room.encrypted event. */ - fun encryptMessage(payloadFields: Map, deviceInfos: List): EncryptedMessage { + fun encryptMessage(payloadFields: Content, deviceInfos: List): EncryptedMessage { val deviceInfoParticipantKey = deviceInfos.associateBy { it.identityKey()!! } val payloadJson = payloadFields.toMutableMap() - payloadJson["sender"] = credentials.userId - payloadJson["sender_device"] = credentials.deviceId!! + payloadJson["sender"] = userId + payloadJson["sender_device"] = deviceId!! // Include the Ed25519 key so that the recipient knows what // device this message came from. From 13cd13a42fa89b39dcb56251344271c4e19ccdd2 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Thu, 16 Apr 2020 17:28:04 +0200 Subject: [PATCH 08/37] Create RoomEncryptorsStore --- .../internal/crypto/DefaultCryptoService.kt | 27 +++---------- .../internal/crypto/RoomEncryptorsStore.kt | 38 +++++++++++++++++++ .../algorithms/megolm/MXMegolmEncryption.kt | 2 +- 3 files changed, 45 insertions(+), 22 deletions(-) create mode 100644 matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt index 61a072ece6..e37af45a73 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt @@ -122,7 +122,8 @@ internal class DefaultCryptoService @Inject constructor( private val myDeviceInfoHolder: Lazy, // the crypto store private val cryptoStore: IMXCryptoStore, - + // Room encryptors store + private val roomEncryptorsStore: RoomEncryptorsStore, // Olm device private val olmDevice: MXOlmDevice, // Set of parameters used to configure/customize the end-to-end crypto. @@ -172,8 +173,6 @@ internal class DefaultCryptoService @Inject constructor( private val uiHandler = Handler(Looper.getMainLooper()) - // MXEncrypting instance for each room. - private val roomEncryptors: MutableMap = HashMap() private val isStarting = AtomicBoolean(false) private val isStarted = AtomicBoolean(false) @@ -512,9 +511,7 @@ internal class DefaultCryptoService @Inject constructor( else -> olmEncryptionFactory.create(roomId) } - synchronized(roomEncryptors) { - roomEncryptors.put(roomId, alg) - } + roomEncryptorsStore.put(roomId, alg) // if encryption was not previously enabled in this room, we will have been // ignoring new device events for these users so far. We may well have @@ -596,16 +593,12 @@ internal class DefaultCryptoService @Inject constructor( internalStart(false) } val userIds = getRoomUserIds(roomId) - var alg = synchronized(roomEncryptors) { - roomEncryptors[roomId] - } + var alg = roomEncryptorsStore.get(roomId) if (alg == null) { val algorithm = getEncryptionAlgorithm(roomId) if (algorithm != null) { if (setEncryptionInRoom(roomId, algorithm, false, userIds)) { - synchronized(roomEncryptors) { - alg = roomEncryptors[roomId] - } + alg = roomEncryptorsStore.get(roomId) } } } @@ -836,16 +829,8 @@ internal class DefaultCryptoService @Inject constructor( * @param event the membership event causing the change */ private fun onRoomMembershipEvent(roomId: String, event: Event) { - val alg: IMXEncrypting? + roomEncryptorsStore.get(roomId) ?: /* No encrypting in this room */ return - synchronized(roomEncryptors) { - alg = roomEncryptors[roomId] - } - - if (null == alg) { - // No encrypting in this room - return - } event.stateKey?.let { userId -> val roomMember: RoomMemberSummary? = event.content.toModel() val membership = roomMember?.membership diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt new file mode 100644 index 0000000000..3b74e62167 --- /dev/null +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2020 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 im.vector.matrix.android.internal.crypto + +import im.vector.matrix.android.internal.crypto.algorithms.IMXEncrypting +import javax.inject.Inject + +internal class RoomEncryptorsStore @Inject constructor() { + + // MXEncrypting instance for each room. + private val roomEncryptors = mutableMapOf() + + fun put(roomId: String, alg: IMXEncrypting) { + synchronized(roomEncryptors) { + roomEncryptors.put(roomId, alg) + } + } + + fun get(roomId: String): IMXEncrypting? { + return synchronized(roomEncryptors) { + roomEncryptors[roomId] + } + } +} diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt index a2d21c4f89..0ce2269bde 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt @@ -40,7 +40,7 @@ import timber.log.Timber internal class MXMegolmEncryption( // The id of the room we will be sending to. - private var roomId: String, + private val roomId: String, private val olmDevice: MXOlmDevice, private val defaultKeysBackupService: DefaultKeysBackupService, private val cryptoStore: IMXCryptoStore, From 6186c22e0263cf2004a5200045edfe52b439edfc Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Fri, 17 Apr 2020 10:01:16 +0200 Subject: [PATCH 09/37] improve code --- .../android/internal/crypto/actions/MessageEncrypter.kt | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt index 9961f40b9a..c1cdbe59f9 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt @@ -58,11 +58,9 @@ internal class MessageEncrypter @Inject constructor( // homeserver signed by the ed25519 key this proves that // the curve25519 key and the ed25519 key are owned by // the same device. - val keysMap = HashMap() - keysMap["ed25519"] = olmDevice.deviceEd25519Key!! - payloadJson["keys"] = keysMap + payloadJson["keys"] = mapOf("ed25519" to olmDevice.deviceEd25519Key!!) - val ciphertext = HashMap() + val ciphertext = mutableMapOf() for ((deviceKey, deviceInfo) in deviceInfoParticipantKey) { val sessionId = olmDevice.getSessionId(deviceKey) From 4d296ddc091ad339ce08d7d35cf09fad02f5490c Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Fri, 17 Apr 2020 17:26:57 +0200 Subject: [PATCH 10/37] Avoid injecting credentials --- .../internal/crypto/DefaultCryptoService.kt | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt index e37af45a73..537dfc3d41 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt @@ -28,7 +28,6 @@ import com.zhuinden.monarchy.Monarchy import dagger.Lazy import im.vector.matrix.android.api.MatrixCallback import im.vector.matrix.android.api.NoOpMatrixCallback -import im.vector.matrix.android.api.auth.data.Credentials import im.vector.matrix.android.api.crypto.MXCryptoConfig import im.vector.matrix.android.api.failure.Failure import im.vector.matrix.android.api.listeners.ProgressListener @@ -79,7 +78,9 @@ import im.vector.matrix.android.internal.crypto.verification.DefaultVerification import im.vector.matrix.android.internal.database.model.EventEntity import im.vector.matrix.android.internal.database.model.EventEntityFields import im.vector.matrix.android.internal.database.query.whereType +import im.vector.matrix.android.internal.di.DeviceId import im.vector.matrix.android.internal.di.MoshiProvider +import im.vector.matrix.android.internal.di.UserId import im.vector.matrix.android.internal.extensions.foldToCallback import im.vector.matrix.android.internal.session.SessionScope import im.vector.matrix.android.internal.session.room.membership.LoadRoomMembersTask @@ -117,8 +118,10 @@ import kotlin.math.max internal class DefaultCryptoService @Inject constructor( // Olm Manager private val olmManager: OlmManager, - // The credentials, - private val credentials: Credentials, + @UserId + private val userId: String, + @DeviceId + private val deviceId: String?, private val myDeviceInfoHolder: Lazy, // the crypto store private val cryptoStore: IMXCryptoStore, @@ -199,7 +202,7 @@ internal class DefaultCryptoService @Inject constructor( this.callback = object : MatrixCallback { override fun onSuccess(data: Unit) { // bg refresh of crypto device - downloadKeys(listOf(credentials.userId), true, NoOpMatrixCallback()) + downloadKeys(listOf(userId), true, NoOpMatrixCallback()) callback.onSuccess(data) } @@ -398,7 +401,7 @@ internal class DefaultCryptoService @Inject constructor( } /** - * Provides the device information for a device id and a user Id + * Provides the device information for a user id and a device Id * * @param userId the user id * @param deviceId the device id @@ -746,7 +749,7 @@ internal class DefaultCryptoService @Inject constructor( } // Was that sent by us? - if (event.senderId != credentials.userId) { + if (event.senderId != userId) { Timber.e("## GOSSIP onSecretSend() : Ignore secret from other user ${event.senderId}") return } @@ -1164,7 +1167,7 @@ internal class DefaultCryptoService @Inject constructor( * ========================================================================================== */ override fun toString(): String { - return "DefaultCryptoService of " + credentials.userId + " (" + credentials.deviceId + ")" + return "DefaultCryptoService of $userId ($deviceId)" } override fun getOutgoingRoomKeyRequest(): List { From f989eed8b0d1bd4e5b1a412342104d00c14ea869 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Mon, 20 Apr 2020 15:37:00 +0200 Subject: [PATCH 11/37] Use @Throws(MXCryptoError::class) --- .../internal/crypto/DefaultCryptoService.kt | 1 + .../android/internal/crypto/MXOlmDevice.kt | 4 ++-- .../crypto/algorithms/IMXDecrypting.kt | 2 ++ .../algorithms/megolm/MXMegolmDecryption.kt | 2 ++ .../crypto/algorithms/olm/MXOlmDecryption.kt | 1 + .../crypto/model/rest/DummyContent.kt | 22 +++++++++++++++++++ 6 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/DummyContent.kt diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt index 537dfc3d41..a52ad40a6e 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt @@ -661,6 +661,7 @@ internal class DefaultCryptoService @Inject constructor( * @param timeline the id of the timeline where the event is decrypted. It is used to prevent replay attack. * @return the MXEventDecryptionResult data, or null in case of error */ + @Throws(MXCryptoError::class) private fun internalDecryptEvent(event: Event, timeline: String): MXEventDecryptionResult { val eventContent = event.content if (eventContent == null) { diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/MXOlmDevice.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/MXOlmDevice.kt index 86f0768a7d..0351c183ce 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/MXOlmDevice.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/MXOlmDevice.kt @@ -625,6 +625,7 @@ internal class MXOlmDevice @Inject constructor( * @param senderKey the base64-encoded curve25519 key of the sender. * @return the decrypting result. Nil if the sessionId is unknown. */ + @Throws(MXCryptoError::class) fun decryptGroupMessage(body: String, roomId: String, timeline: String?, @@ -662,8 +663,7 @@ internal class MXOlmDevice @Inject constructor( adapter.fromJson(payloadString) } catch (e: Exception) { Timber.e("## decryptGroupMessage() : fails to parse the payload") - throw - MXCryptoError.Base(MXCryptoError.ErrorType.BAD_DECRYPTED_FORMAT, MXCryptoError.BAD_DECRYPTED_FORMAT_TEXT_REASON) + throw MXCryptoError.Base(MXCryptoError.ErrorType.BAD_DECRYPTED_FORMAT, MXCryptoError.BAD_DECRYPTED_FORMAT_TEXT_REASON) } return OlmDecryptionResult( diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXDecrypting.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXDecrypting.kt index e9176ad6d9..0babb73842 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXDecrypting.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXDecrypting.kt @@ -17,6 +17,7 @@ package im.vector.matrix.android.internal.crypto.algorithms +import im.vector.matrix.android.api.session.crypto.MXCryptoError import im.vector.matrix.android.api.session.events.model.Event import im.vector.matrix.android.internal.crypto.IncomingRoomKeyRequest import im.vector.matrix.android.internal.crypto.IncomingSecretShareRequest @@ -35,6 +36,7 @@ internal interface IMXDecrypting { * @param timeline the id of the timeline where the event is decrypted. It is used to prevent replay attack. * @return the decryption information, or an error */ + @Throws(MXCryptoError::class) fun decryptEvent(event: Event, timeline: String): MXEventDecryptionResult /** diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt index 1d7a2765fa..3e7ce4df06 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt @@ -63,6 +63,7 @@ internal class MXMegolmDecryption(private val userId: String, */ private var pendingEvents: MutableMap>> = HashMap() + @Throws(MXCryptoError::class) override fun decryptEvent(event: Event, timeline: String): MXEventDecryptionResult { // If cross signing is enabled, we don't send request until the keys are trusted // There could be a race effect here when xsigning is enabled, we should ensure that keys was downloaded once @@ -70,6 +71,7 @@ internal class MXMegolmDecryption(private val userId: String, return decryptEvent(event, timeline, requestOnFail) } + @Throws(MXCryptoError::class) private fun decryptEvent(event: Event, timeline: String, requestKeysOnFail: Boolean): MXEventDecryptionResult { if (event.roomId.isNullOrBlank()) { throw MXCryptoError.Base(MXCryptoError.ErrorType.MISSING_FIELDS, MXCryptoError.MISSING_FIELDS_REASON) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmDecryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmDecryption.kt index 0a8ef3993b..8ef527fa05 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmDecryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmDecryption.kt @@ -38,6 +38,7 @@ internal class MXOlmDecryption( private val userId: String) : IMXDecrypting { + @Throws(MXCryptoError::class) override fun decryptEvent(event: Event, timeline: String): MXEventDecryptionResult { val olmEventContent = event.content.toModel() ?: run { Timber.e("## decryptEvent() : bad event format") diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/DummyContent.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/DummyContent.kt new file mode 100644 index 0000000000..b52354768d --- /dev/null +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/DummyContent.kt @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2020 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 im.vector.matrix.android.internal.crypto.model.rest + +/** + * Class representing the dummy content + * Ref: https://matrix.org/docs/spec/client_server/latest#id82 + */ +typealias DummyContent = Unit From 91cf4b647d362e756fe309c577f289a46919d961 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Mon, 20 Apr 2020 15:37:23 +0200 Subject: [PATCH 12/37] var -> val --- .../android/internal/crypto/algorithms/olm/MXOlmEncryption.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt index 899e884e0d..b3d26df829 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt @@ -29,7 +29,7 @@ import im.vector.matrix.android.internal.crypto.model.CryptoDeviceInfo import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore internal class MXOlmEncryption( - private var roomId: String, + private val roomId: String, private val olmDevice: MXOlmDevice, private val cryptoStore: IMXCryptoStore, private val messageEncrypter: MessageEncrypter, From ddb00ba23a7d95e03d4026d8091fdb77ede45782 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Mon, 20 Apr 2020 15:55:26 +0200 Subject: [PATCH 13/37] Enable Timber log in integration tests --- .../java/im/vector/matrix/android/common/CommonTestHelper.kt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt index 3cf03fff53..965255e045 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt @@ -44,6 +44,7 @@ import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue +import timber.log.Timber import java.util.ArrayList import java.util.UUID import java.util.concurrent.CountDownLatch @@ -58,6 +59,8 @@ class CommonTestHelper(context: Context) { val matrix: Matrix init { + Timber.plant(Timber.DebugTree()) + Matrix.initialize(context, MatrixConfiguration("TestFlavor")) matrix = Matrix.getInstance(context) From 3615ca6b95def9adb37e652a451adc3f1b9a8de7 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Mon, 20 Apr 2020 16:02:29 +0200 Subject: [PATCH 14/37] VersionName can be null when running integration test --- .../vector/matrix/android/internal/network/UserAgentHolder.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/UserAgentHolder.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/UserAgentHolder.kt index 0f3da0c834..15c91a629a 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/UserAgentHolder.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/UserAgentHolder.kt @@ -51,7 +51,7 @@ internal class UserAgentHolder @Inject constructor(private val context: Context, appName = pm.getApplicationLabel(appInfo).toString() val pkgInfo = pm.getPackageInfo(context.applicationContext.packageName, 0) - appVersion = pkgInfo.versionName + appVersion = pkgInfo.versionName ?: "" // Use appPackageName instead of appName if appName contains any non-ASCII character if (!appName.matches("\\A\\p{ASCII}*\\z".toRegex())) { From a6368c473e57e6d92aaa24bb4ae4ad7294d81e3d Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Mon, 20 Apr 2020 17:44:45 +0200 Subject: [PATCH 15/37] Restart broken Olm sessions ([MSC1719](https://github.com/matrix-org/matrix-doc/pull/1719)) --- CHANGES.md | 1 + .../android/internal/crypto/UnwedgingTest.kt | 6 ++- .../api/session/events/model/EventType.kt | 3 ++ .../internal/crypto/DefaultCryptoService.kt | 52 +++++++++++++++++- .../crypto/IncomingGossipingRequestManager.kt | 53 +++++++++++++++---- .../internal/crypto/RoomEncryptorsStore.kt | 2 + .../EnsureOlmSessionsForDevicesAction.kt | 11 ++-- .../crypto/algorithms/IMXEncrypting.kt | 16 ++++++ .../algorithms/megolm/MXMegolmDecryption.kt | 22 ++++++++ .../algorithms/megolm/MXMegolmEncryption.kt | 45 ++++++++++++++++ .../crypto/algorithms/olm/MXOlmEncryption.kt | 5 ++ .../model/OlmInboundGroupSessionWrapper.kt | 7 ++- 12 files changed, 202 insertions(+), 21 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 0c1d209f61..dc5d6f4a96 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -22,6 +22,7 @@ Improvements 🙌: - Emoji Verification | It's not the same butterfly! (#1220) - Cross-Signing | Composer decoration: shields (#1077) - Cross-Signing | Migrate existing keybackup to cross signing with 4S from mobile (#1197) + - Restart broken Olm sessions ([MSC1719](https://github.com/matrix-org/matrix-doc/pull/1719)) Bugfix 🐛: - Fix summary notification staying after "mark as read" diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt index 4a28a77986..123c8a5c88 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt @@ -27,10 +27,12 @@ import im.vector.matrix.android.common.CryptoTestHelper import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldBeEqualTo import org.junit.Before +import org.junit.BeforeClass import org.junit.FixMethodOrder import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters +import timber.log.Timber import java.util.concurrent.CountDownLatch /** @@ -99,13 +101,13 @@ class UnwedgingTest : InstrumentedTest { override fun onTimelineUpdated(snapshot: List) { val decryptedEventReceivedByBob = snapshot.filter { it.root.getClearType() == EventType.MESSAGE } + Timber.d("Bob can now decrypt ${decryptedEventReceivedByBob.size} messages") if (decryptedEventReceivedByBob.size == 3) { bobFinalLatch.countDown() } } } bobTimeline.addListener(bobHasThreeDecryptedEventsListener) - var latch = CountDownLatch(1) var bobEventsListener = createEventListener(latch, 1) @@ -128,7 +130,7 @@ class UnwedgingTest : InstrumentedTest { sessionIdsForBob!!.size shouldBe 1 val olmSession = aliceCryptoStore.getDeviceSession(sessionIdsForBob.first(), bobSession.cryptoService().getMyDevice().identityKey()!!)!! - // Sam join the room + // Sam join the room, so it will force a new session creation val samSession = mCryptoTestHelper.createSamAccountAndInviteToTheRoom(roomFromAlicePOV) latch = CountDownLatch(1) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/events/model/EventType.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/events/model/EventType.kt index 9a3107a8ca..3cdd433516 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/events/model/EventType.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/events/model/EventType.kt @@ -81,6 +81,9 @@ object EventType { // Relation Events const val REACTION = "m.reaction" + // Unwedging + internal const val DUMMY = "m.dummy" + private val STATE_EVENTS = listOf( STATE_ROOM_NAME, STATE_ROOM_TOPIC, diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt index a52ad40a6e..476af38ce7 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt @@ -48,6 +48,7 @@ import im.vector.matrix.android.api.session.room.model.RoomMemberSummary import im.vector.matrix.android.internal.crypto.actions.MegolmSessionDataImporter import im.vector.matrix.android.internal.crypto.actions.SetDeviceVerificationAction import im.vector.matrix.android.internal.crypto.algorithms.IMXEncrypting +import im.vector.matrix.android.internal.crypto.algorithms.megolm.MXMegolmDecryption import im.vector.matrix.android.internal.crypto.algorithms.megolm.MXMegolmEncryptionFactory import im.vector.matrix.android.internal.crypto.algorithms.olm.MXOlmEncryptionFactory import im.vector.matrix.android.internal.crypto.crosssigning.DefaultCrossSigningService @@ -179,6 +180,10 @@ internal class DefaultCryptoService @Inject constructor( private val isStarting = AtomicBoolean(false) private val isStarted = AtomicBoolean(false) + // The date of the last time we forced establishment + // of a new session for each user:device. + private val lastNewSessionForcedDates = MXUsersDevicesMap() + fun onStateEvent(roomId: String, event: Event) { when { event.getClearType() == EventType.STATE_ROOM_ENCRYPTION -> onRoomEncryptionEvent(roomId, event) @@ -675,11 +680,52 @@ internal class DefaultCryptoService @Inject constructor( Timber.e("## decryptEvent() : $reason") throw MXCryptoError.Base(MXCryptoError.ErrorType.UNABLE_TO_DECRYPT, reason) } else { - return alg.decryptEvent(event, timeline) + try { + return alg.decryptEvent(event, timeline) + } catch (mxCryptoError: MXCryptoError) { + if (mxCryptoError is MXCryptoError.Base + && mxCryptoError.errorType == MXCryptoError.ErrorType.BAD_ENCRYPTED_MESSAGE + && alg is MXMegolmDecryption) { + // TODO Do it on decryption thread like on iOS? + markOlmSessionForUnwedging(event, alg) + } + throw mxCryptoError + } } } } + private fun markOlmSessionForUnwedging(event: Event, mxMegolmDecryption: MXMegolmDecryption) { + val senderId = event.senderId ?: return + val encryptedMessage = event.content.toModel() ?: return + val deviceKey = encryptedMessage.senderKey ?: return + encryptedMessage.algorithm?.takeIf { it == MXCRYPTO_ALGORITHM_MEGOLM } ?: return + + if (senderId == userId + && deviceKey == olmDevice.deviceCurve25519Key) { + Timber.d("[MXCrypto] markOlmSessionForUnwedging: Do not unwedge ourselves") + return + } + + val lastForcedDate = lastNewSessionForcedDates.getObject(senderId, deviceKey) ?: 0 + val now = System.currentTimeMillis() + if (now - lastForcedDate < CRYPTO_MIN_FORCE_SESSION_PERIOD_MILLIS) { + Timber.d("[MXCrypto] markOlmSessionForUnwedging: New session already forced with device at $lastForcedDate. Not forcing another") + return + } + + // Establish a new olm session with this device since we're failing to decrypt messages + // on a current session. + val deviceInfo = getDeviceInfo(senderId, deviceKey) ?: return Unit.also { + Timber.d("[MXCrypto] markOlmSessionForUnwedging: Couldn't find device for identity key $deviceKey: not re-establishing session") + } + + Timber.d("[MXCrypto] markOlmSessionForUnwedging from $senderId:${deviceInfo.deviceId}") + lastNewSessionForcedDates.setObject(senderId, deviceKey, now) + + mxMegolmDecryption.markOlmSessionForUnwedging(senderId, deviceInfo) + } + /** * Reset replay attack data for the given timeline. * @@ -1189,4 +1235,8 @@ internal class DefaultCryptoService @Inject constructor( @VisibleForTesting val cryptoStoreForTesting = cryptoStore + + companion object { + const val CRYPTO_MIN_FORCE_SESSION_PERIOD_MILLIS = 3_600_000 // one hour + } } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/IncomingGossipingRequestManager.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/IncomingGossipingRequestManager.kt index da596960dd..b17143d93d 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/IncomingGossipingRequestManager.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/IncomingGossipingRequestManager.kt @@ -32,7 +32,10 @@ import im.vector.matrix.android.internal.crypto.model.rest.GossipingToDeviceObje import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore import im.vector.matrix.android.internal.di.SessionId import im.vector.matrix.android.internal.session.SessionScope +import im.vector.matrix.android.internal.util.MatrixCoroutineDispatchers import im.vector.matrix.android.internal.worker.WorkerParamsFactory +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject @@ -43,7 +46,10 @@ internal class IncomingGossipingRequestManager @Inject constructor( private val cryptoStore: IMXCryptoStore, private val cryptoConfig: MXCryptoConfig, private val gossipingWorkManager: GossipingWorkManager, - private val roomDecryptorProvider: RoomDecryptorProvider) { + private val roomEncryptorsStore: RoomEncryptorsStore, + private val roomDecryptorProvider: RoomDecryptorProvider, + private val coroutineDispatchers: MatrixCoroutineDispatchers, + private val cryptoCoroutineScope: CoroutineScope) { // list of IncomingRoomKeyRequests/IncomingRoomKeyRequestCancellations // we received in the current sync. @@ -178,17 +184,42 @@ internal class IncomingGossipingRequestManager @Inject constructor( } private fun processIncomingRoomKeyRequest(request: IncomingRoomKeyRequest) { - val userId = request.userId - val deviceId = request.deviceId - val body = request.requestBody - val roomId = body!!.roomId - val alg = body.algorithm + val userId = request.userId ?: return + val deviceId = request.deviceId ?: return + val body = request.requestBody ?: return + val roomId = body.roomId ?: return + val alg = body.algorithm ?: return Timber.v("## GOSSIP processIncomingRoomKeyRequest from $userId:$deviceId for $roomId / ${body.sessionId} id ${request.requestId}") - if (userId == null || credentials.userId != userId) { - // TODO: determine if we sent this device the keys already: in - Timber.w("## GOSSIP processReceivedGossipingRequests() : Ignoring room key request from other user for now") - cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) + if (credentials.userId != userId) { + Timber.w("## GOSSIP processReceivedGossipingRequests() : room key request from other user") + val senderKey = body.senderKey ?: return Unit + .also { Timber.w("missing senderKey") } + .also { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) } + val sessionId = body.sessionId ?: return Unit + .also { Timber.w("missing sessionId") } + .also { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) } + + if (alg != MXCRYPTO_ALGORITHM_MEGOLM) { + return Unit + .also { Timber.w("Only megolm is accepted here") } + .also { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) } + } + + val roomEncryptor = roomEncryptorsStore.get(roomId) ?: return Unit + .also { Timber.w("no room Encryptor") } + .also { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) } + + cryptoCoroutineScope.launch(coroutineDispatchers.crypto) { + val isSuccess = roomEncryptor.reshareKey(sessionId, userId, deviceId, senderKey) + + if (isSuccess) { + cryptoStore.updateGossipingRequestState(request, GossipingRequestState.ACCEPTED) + } else { + cryptoStore.updateGossipingRequestState(request, GossipingRequestState.UNABLE_TO_PROCESS) + } + } + cryptoStore.updateGossipingRequestState(request, GossipingRequestState.RE_REQUESTED) return } // TODO: should we queue up requests we don't yet have keys for, in case they turn up later? @@ -219,7 +250,7 @@ internal class IncomingGossipingRequestManager @Inject constructor( cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) } // if the device is verified already, share the keys - val device = cryptoStore.getUserDevice(userId, deviceId!!) + val device = cryptoStore.getUserDevice(userId, deviceId) if (device != null) { if (device.isVerified) { Timber.v("## GOSSIP processReceivedGossipingRequests() : device is already verified: sharing keys") diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt index 3b74e62167..52a324d68d 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt @@ -17,8 +17,10 @@ package im.vector.matrix.android.internal.crypto import im.vector.matrix.android.internal.crypto.algorithms.IMXEncrypting +import im.vector.matrix.android.internal.session.SessionScope import javax.inject.Inject +@SessionScope internal class RoomEncryptorsStore @Inject constructor() { // MXEncrypting instance for each room. diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt index e1cac0d75f..d856331189 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt @@ -25,10 +25,11 @@ import im.vector.matrix.android.internal.crypto.tasks.ClaimOneTimeKeysForUsersDe import timber.log.Timber import javax.inject.Inject -internal class EnsureOlmSessionsForDevicesAction @Inject constructor(private val olmDevice: MXOlmDevice, - private val oneTimeKeysForUsersDeviceTask: ClaimOneTimeKeysForUsersDeviceTask) { +internal class EnsureOlmSessionsForDevicesAction @Inject constructor( + private val olmDevice: MXOlmDevice, + private val oneTimeKeysForUsersDeviceTask: ClaimOneTimeKeysForUsersDeviceTask) { - suspend fun handle(devicesByUser: Map>): MXUsersDevicesMap { + suspend fun handle(devicesByUser: Map>, force: Boolean = false): MXUsersDevicesMap { val devicesWithoutSession = ArrayList() val results = MXUsersDevicesMap() @@ -40,7 +41,7 @@ internal class EnsureOlmSessionsForDevicesAction @Inject constructor(private val val sessionId = olmDevice.getSessionId(key!!) - if (sessionId.isNullOrEmpty()) { + if (sessionId.isNullOrEmpty() || force) { devicesWithoutSession.add(deviceInfo) } @@ -80,7 +81,7 @@ internal class EnsureOlmSessionsForDevicesAction @Inject constructor(private val if (null != deviceIds) { for (deviceId in deviceIds) { val olmSessionResult = results.getObject(userId, deviceId) - if (olmSessionResult!!.sessionId != null) { + if (olmSessionResult!!.sessionId != null && !force) { // We already have a result for this device continue } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXEncrypting.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXEncrypting.kt index 555ce9dfd4..65119362bc 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXEncrypting.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXEncrypting.kt @@ -33,4 +33,20 @@ internal interface IMXEncrypting { * @return the encrypted content */ suspend fun encryptEventContent(eventContent: Content, eventType: String, userIds: List): Content + + /** + * Re-shares a session key with devices if the key has already been + * sent to them. + * + * @param sessionId The id of the outbound session to share. + * @param userId The id of the user who owns the target device. + * @param deviceId The id of the target device. + * @param senderKey The key of the originating device for the session. + * + * @return true in case of success + */ + suspend fun reshareKey(sessionId: String, + userId: String, + deviceId: String, + senderKey: String): Boolean } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt index 3e7ce4df06..815a4f7d12 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt @@ -31,6 +31,7 @@ import im.vector.matrix.android.internal.crypto.actions.EnsureOlmSessionsForDevi import im.vector.matrix.android.internal.crypto.actions.MessageEncrypter import im.vector.matrix.android.internal.crypto.algorithms.IMXDecrypting import im.vector.matrix.android.internal.crypto.keysbackup.DefaultKeysBackupService +import im.vector.matrix.android.internal.crypto.model.CryptoDeviceInfo import im.vector.matrix.android.internal.crypto.model.MXUsersDevicesMap import im.vector.matrix.android.internal.crypto.model.event.EncryptedEventContent import im.vector.matrix.android.internal.crypto.model.event.RoomKeyContent @@ -346,4 +347,25 @@ internal class MXMegolmDecryption(private val userId: String, } } } + + fun markOlmSessionForUnwedging(senderId: String, deviceInfo: CryptoDeviceInfo) { + cryptoCoroutineScope.launch(coroutineDispatchers.crypto) { + ensureOlmSessionsForDevicesAction.handle(mapOf(senderId to listOf(deviceInfo)), force = true) + + // Now send a blank message on that session so the other side knows about it. + // (The keyshare request is sent in the clear so that won't do) + // We send this first such that, as long as the toDevice messages arrive in the + // same order we sent them, the other end will get this first, set up the new session, + // then get the keyshare request and send the key over this new session (because it + // is the session it has most recently received a message on). + val payloadJson = mapOf("type" to EventType.DUMMY) + + val encodedPayload = messageEncrypter.encryptMessage(payloadJson, listOf(deviceInfo)) + val sendToDeviceMap = MXUsersDevicesMap() + sendToDeviceMap.setObject(senderId, deviceInfo.deviceId, encodedPayload) + Timber.v("## markOlmSessionForUnwedging() : sending to $senderId:${deviceInfo.deviceId}") + val sendToDeviceParams = SendToDeviceTask.Params(EventType.ENCRYPTED, sendToDeviceMap) + sendToDeviceTask.execute(sendToDeviceParams) + } + } } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt index 0ce2269bde..addb8c2f76 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt @@ -305,4 +305,49 @@ internal class MXMegolmEncryption( throw MXCryptoError.UnknownDevice(unknownDevices) } } + + override suspend fun reshareKey(sessionId: String, + userId: String, + deviceId: String, + senderKey: String): Boolean { + Timber.d("[MXMegolmEncryption] reshareKey: $sessionId to $userId:$deviceId") + val deviceInfo = cryptoStore.getUserDevice(userId, deviceId) ?: return false + .also { Timber.w("Device not found") } + + // Get the chain index of the key we previously sent this device + val chainIndex = outboundSession?.sharedWithDevices?.getObject(userId, deviceId)?.toLong() ?: return false + .also { Timber.w("[MXMegolmEncryption] reshareKey : ERROR : Never share megolm with this device") } + + val devicesByUser = mapOf(userId to listOf(deviceInfo)) + val usersDeviceMap = ensureOlmSessionsForDevicesAction.handle(devicesByUser) + val olmSessionResult = usersDeviceMap.getObject(userId, deviceId) + olmSessionResult?.sessionId + ?: // no session with this device, probably because there were no one-time keys. + // ensureOlmSessionsForDevicesAction has already done the logging, so just skip it. + return false + + Timber.d("[MXMegolmEncryption] reshareKey: sharing keys for session $senderKey|$sessionId:$chainIndex with device $userId:$deviceId") + + val payloadJson = mutableMapOf("type" to EventType.FORWARDED_ROOM_KEY) + + runCatching { olmDevice.getInboundGroupSession(sessionId, senderKey, roomId) } + .fold( + { + // TODO + payloadJson["content"] = it.exportKeys(chainIndex) ?: "" + }, + { + // TODO + } + + ) + + val encodedPayload = messageEncrypter.encryptMessage(payloadJson, listOf(deviceInfo)) + val sendToDeviceMap = MXUsersDevicesMap() + sendToDeviceMap.setObject(userId, deviceId, encodedPayload) + Timber.v("## shareKeysWithDevice() : sending to $userId:$deviceId") + val sendToDeviceParams = SendToDeviceTask.Params(EventType.ENCRYPTED, sendToDeviceMap) + sendToDeviceTask.execute(sendToDeviceParams) + return true + } } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt index b3d26df829..b1181fc067 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt @@ -78,4 +78,9 @@ internal class MXOlmEncryption( deviceListManager.downloadKeys(users, false) ensureOlmSessionsForUsersAction.handle(users) } + + override suspend fun reshareKey(sessionId: String, userId: String, deviceId: String, senderKey: String): Boolean { + // No need for olm + return false + } } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/OlmInboundGroupSessionWrapper.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/OlmInboundGroupSessionWrapper.kt index cf1a3b237a..9be08d9f2d 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/OlmInboundGroupSessionWrapper.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/OlmInboundGroupSessionWrapper.kt @@ -103,10 +103,11 @@ class OlmInboundGroupSessionWrapper : Serializable { /** * Export the inbound group session keys + * @param index the index to export. If null, the first known index will be used * * @return the inbound group session as MegolmSessionData if the operation succeeds */ - fun exportKeys(): MegolmSessionData? { + fun exportKeys(index: Long? = null): MegolmSessionData? { return try { if (null == forwardingCurve25519KeyChain) { forwardingCurve25519KeyChain = ArrayList() @@ -116,6 +117,8 @@ class OlmInboundGroupSessionWrapper : Serializable { return null } + val wantedIndex = index ?: olmInboundGroupSession!!.firstKnownIndex + MegolmSessionData( senderClaimedEd25519Key = keysClaimed?.get("ed25519"), forwardingCurve25519KeyChain = ArrayList(forwardingCurve25519KeyChain!!), @@ -123,7 +126,7 @@ class OlmInboundGroupSessionWrapper : Serializable { senderClaimedKeys = keysClaimed, roomId = roomId, sessionId = olmInboundGroupSession!!.sessionIdentifier(), - sessionKey = olmInboundGroupSession!!.export(olmInboundGroupSession!!.firstKnownIndex), + sessionKey = olmInboundGroupSession!!.export(wantedIndex), algorithm = MXCRYPTO_ALGORITHM_MEGOLM ) } catch (e: Exception) { From c1acb1af66e882dc1d7eabc691b62981a0369079 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 21 Apr 2020 00:23:01 +0200 Subject: [PATCH 16/37] Add integration test for change password feature --- .../android/account/ChangePasswordTest.kt | 58 +++++++++++++++++++ .../matrix/android/common/CommonTestHelper.kt | 38 +++++++++++- 2 files changed, 93 insertions(+), 3 deletions(-) create mode 100644 matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/account/ChangePasswordTest.kt diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/account/ChangePasswordTest.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/account/ChangePasswordTest.kt new file mode 100644 index 0000000000..981385f3c7 --- /dev/null +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/account/ChangePasswordTest.kt @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2020 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 im.vector.matrix.android.account + +import im.vector.matrix.android.InstrumentedTest +import im.vector.matrix.android.common.CommonTestHelper +import im.vector.matrix.android.common.SessionTestParams +import im.vector.matrix.android.common.TestConstants +import org.junit.FixMethodOrder +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 +import org.junit.runners.MethodSorters + +@RunWith(JUnit4::class) +@FixMethodOrder(MethodSorters.JVM) +class ChangePasswordTest : InstrumentedTest { + + private val commonTestHelper = CommonTestHelper(context()) + + companion object { + private const val NEW_PASSWORD = "this is a new password" + } + + @Test + fun changePasswordTest() { + val session = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = false)) + + // Change password + commonTestHelper.doSync { + session.changePassword(TestConstants.PASSWORD, NEW_PASSWORD, it) + } + + // Try to login with the previous password, it will fail + commonTestHelper.logAccountBadPassword(session.myUserId, TestConstants.PASSWORD) + + // Try to login with the new password, should work + val session2 = commonTestHelper.logIntoAccount(session.myUserId, NEW_PASSWORD, SessionTestParams(withInitialSync = false)) + + + commonTestHelper.signOutAndClose(session) + commonTestHelper.signOutAndClose(session2) + } +} diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt index 3cf03fff53..86378ee2fb 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt @@ -26,6 +26,7 @@ import im.vector.matrix.android.api.MatrixConfiguration import im.vector.matrix.android.api.auth.data.HomeServerConnectionConfig import im.vector.matrix.android.api.auth.data.LoginFlowResult import im.vector.matrix.android.api.auth.registration.RegistrationResult +import im.vector.matrix.android.api.failure.isInvalidPassword import im.vector.matrix.android.api.session.Session import im.vector.matrix.android.api.session.events.model.EventType import im.vector.matrix.android.api.session.events.model.LocalEcho @@ -41,6 +42,7 @@ import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking +import org.amshove.kluent.shouldBeTrue import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue @@ -183,9 +185,9 @@ class CommonTestHelper(context: Context) { * @param testParams test params about the session * @return the session associated with the existing account */ - private fun logIntoAccount(userId: String, - password: String, - testParams: SessionTestParams): Session { + fun logIntoAccount(userId: String, + password: String, + testParams: SessionTestParams): Session { val session = logAccountAndSync(userId, password, testParams) assertNotNull(session) return session @@ -260,6 +262,36 @@ class CommonTestHelper(context: Context) { return session } + /** + * Log into the account using a wrong password + * + * @param userName the account username + * @param badPassword an incorrect password + */ + fun logAccountBadPassword(userName: String, + badPassword: String) { + val hs = createHomeServerConfig() + + doSync { + matrix.authenticationService + .getLoginFlow(hs, it) + } + + var requestFailure: Throwable? = null + val latch = CountDownLatch(1) + matrix.authenticationService + .getLoginWizard() + .login(userName, badPassword, "myDevice", object : TestMatrixCallback(latch, onlySuccessful = false) { + override fun onFailure(failure: Throwable) { + requestFailure = failure + super.onFailure(failure) + } + }) + await(latch) + + requestFailure!!.isInvalidPassword().shouldBeTrue() + } + /** * Await for a latch and ensure the result is true * From 59280ed18eede32ca994229e90435f8c6d8e4326 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 21 Apr 2020 00:29:02 +0200 Subject: [PATCH 17/37] Small improvement in documentation --- docs/notifications.md | 4 ++-- docs/signin.md | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/notifications.md b/docs/notifications.md index 328eb86954..8efcb87bf3 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -38,10 +38,10 @@ When the client receives the new information, it immediately sends another reque This effectively emulates a server push feature. The HTTP long Polling can be fine tuned in the **SDK** using two parameters: -* timout (Sync request timeout) +* timeout (Sync request timeout) * delay (Delay between each sync) -**timeout** is a server paramter, defined by: +**timeout** is a server parameter, defined by: ``` The maximum time to wait, in milliseconds, before returning this request.` If no events (or other data) become available before this time elapses, the server will return a response with empty fields. diff --git a/docs/signin.md b/docs/signin.md index 245ea444f6..e7368137ae 100644 --- a/docs/signin.md +++ b/docs/signin.md @@ -57,7 +57,7 @@ We get credential (200) ```json { - "user_id": "@benoit0816:matrix.org", + "user_id": "@alice:matrix.org", "access_token": "MDAxOGxvY2F0aW9uIG1hdHREDACTEDb2l0MDgxNjptYXRyaXgub3JnCjAwMTZjaWQgdHlwZSA9IGFjY2VzcwowMDIxY2lkIG5vbmNlID0gfnYrSypfdTtkNXIuNWx1KgowMDJmc2lnbmF0dXJlIOsh1XqeAkXexh4qcofl_aR4kHJoSOWYGOhE7-ubX-DZCg", "home_server": "matrix.org", "device_id": "GTVREDALBF", @@ -128,6 +128,8 @@ We get the credentials (200) } ``` +It's worth noting that the response from the homeserver contains the userId of Alice. + ### Login with Msisdn Not supported yet in RiotX From c39a0e4fd51ae761cb97720c0375cfc7aab53893 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 21 Apr 2020 00:29:44 +0200 Subject: [PATCH 18/37] timout -> timeout --- .../matrix/android/common/CommonTestHelper.kt | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt index 86378ee2fb..f5027ec7b1 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt @@ -278,16 +278,16 @@ class CommonTestHelper(context: Context) { } var requestFailure: Throwable? = null - val latch = CountDownLatch(1) - matrix.authenticationService - .getLoginWizard() - .login(userName, badPassword, "myDevice", object : TestMatrixCallback(latch, onlySuccessful = false) { - override fun onFailure(failure: Throwable) { - requestFailure = failure - super.onFailure(failure) - } - }) - await(latch) + waitWithLatch { latch -> + matrix.authenticationService + .getLoginWizard() + .login(userName, badPassword, "myDevice", object : TestMatrixCallback(latch, onlySuccessful = false) { + override fun onFailure(failure: Throwable) { + requestFailure = failure + super.onFailure(failure) + } + }) + } requestFailure!!.isInvalidPassword().shouldBeTrue() } @@ -298,8 +298,8 @@ class CommonTestHelper(context: Context) { * @param latch * @throws InterruptedException */ - fun await(latch: CountDownLatch, timout: Long? = TestConstants.timeOutMillis) { - assertTrue(latch.await(timout ?: TestConstants.timeOutMillis, TimeUnit.MILLISECONDS)) + fun await(latch: CountDownLatch, timeout: Long? = TestConstants.timeOutMillis) { + assertTrue(latch.await(timeout ?: TestConstants.timeOutMillis, TimeUnit.MILLISECONDS)) } fun retryPeriodicallyWithLatch(latch: CountDownLatch, condition: (() -> Boolean)) { @@ -314,10 +314,10 @@ class CommonTestHelper(context: Context) { } } - fun waitWithLatch(timout: Long? = TestConstants.timeOutMillis, block: (CountDownLatch) -> Unit) { + fun waitWithLatch(timeout: Long? = TestConstants.timeOutMillis, block: (CountDownLatch) -> Unit) { val latch = CountDownLatch(1) block(latch) - await(latch, timout) + await(latch, timeout) } // Transform a method with a MatrixCallback to a synchronous method From eca3bf08172225f3c28ce14d68ce556f2fb44cf8 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 21 Apr 2020 13:49:36 +0200 Subject: [PATCH 19/37] typo --- .../matrix/android/internal/session/signout/SignOutTask.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/signout/SignOutTask.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/signout/SignOutTask.kt index b14a7758c5..6945ac494e 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/signout/SignOutTask.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/signout/SignOutTask.kt @@ -44,7 +44,7 @@ import javax.inject.Inject internal interface SignOutTask : Task { data class Params( - val sigOutFromHomeserver: Boolean + val signOutFromHomeserver: Boolean ) } @@ -67,7 +67,7 @@ internal class DefaultSignOutTask @Inject constructor( override suspend fun execute(params: SignOutTask.Params) { // It should be done even after a soft logout, to be sure the deviceId is deleted on the - if (params.sigOutFromHomeserver) { + if (params.signOutFromHomeserver) { Timber.d("SignOut: send request...") try { executeRequest(eventBus) { From 3163bc8b8056d68ced9517db227ac79696e0fe59 Mon Sep 17 00:00:00 2001 From: onurays Date: Tue, 21 Apr 2020 15:25:48 +0300 Subject: [PATCH 20/37] Add user to direct chat by user id. Fixes #1065 --- CHANGES.md | 1 + .../createdirect/DirectoryUsersController.kt | 17 ++++++++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 0c1d209f61..91ebeecaa7 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -35,6 +35,7 @@ Bugfix 🐛: - Local echo are not updated in timeline (for failed & encrypted states) - Render image event even if thumbnail_info does not have mimetype defined (#1209) - Fix issue with media path (#1227) + - Add user to direct chat by user id (#1065) Translations 🗣: - diff --git a/vector/src/main/java/im/vector/riotx/features/createdirect/DirectoryUsersController.kt b/vector/src/main/java/im/vector/riotx/features/createdirect/DirectoryUsersController.kt index 016806f319..fd943b6447 100644 --- a/vector/src/main/java/im/vector/riotx/features/createdirect/DirectoryUsersController.kt +++ b/vector/src/main/java/im/vector/riotx/features/createdirect/DirectoryUsersController.kt @@ -23,6 +23,7 @@ import com.airbnb.mvrx.Fail import com.airbnb.mvrx.Loading import com.airbnb.mvrx.Success import com.airbnb.mvrx.Uninitialized +import im.vector.matrix.android.api.MatrixPatterns import im.vector.matrix.android.api.session.Session import im.vector.matrix.android.api.session.user.model.User import im.vector.matrix.android.api.util.toMatrixItem @@ -56,15 +57,25 @@ class DirectoryUsersController @Inject constructor(private val session: Session, override fun buildModels() { val currentState = state ?: return val hasSearch = currentState.directorySearchTerm.isNotBlank() - val asyncUsers = currentState.directoryUsers - when (asyncUsers) { + when (val asyncUsers = currentState.directoryUsers) { is Uninitialized -> renderEmptyState(false) is Loading -> renderLoading() - is Success -> renderSuccess(asyncUsers(), currentState.selectedUsers.map { it.userId }, hasSearch) + is Success -> renderSuccess(getAsyncUsers(currentState), currentState.selectedUsers.map { it.userId }, hasSearch) is Fail -> renderFailure(asyncUsers.error) } } + private fun getAsyncUsers(currentState: CreateDirectRoomViewState): List { + return currentState + .directoryUsers() + ?.toMutableList() + ?.apply { + currentState.directorySearchTerm + .takeIf { MatrixPatterns.isUserId(it) } + ?.let { add(User(it)) } + } ?: emptyList() + } + private fun renderLoading() { loadingItem { id("loading") From 045e3d7bae1f6b6ce75791a0efe8d6dcc0366c95 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 21 Apr 2020 20:31:54 +0200 Subject: [PATCH 21/37] Account deactivation (with password only) (#35) --- CHANGES.md | 1 + .../api/session/account/AccountService.kt | 19 ++- .../internal/session/account/AccountAPI.kt | 8 ++ .../internal/session/account/AccountModule.kt | 3 + .../account/DeactivateAccountParams.kt | 40 ++++++ .../session/account/DeactivateAccountTask.kt | 77 +++++++++++ .../session/account/DefaultAccountService.kt | 9 ++ .../im/vector/riotx/core/di/FragmentModule.kt | 7 + .../im/vector/riotx/features/MainActivity.kt | 16 ++- .../features/settings/VectorPreferences.kt | 1 - .../settings/VectorSettingsActivity.kt | 13 +- .../settings/VectorSettingsGeneralFragment.kt | 13 -- .../deactivation/DeactivateAccountFragment.kt | 124 ++++++++++++++++++ .../DeactivateAccountViewEvents.kt | 30 +++++ .../DeactivateAccountViewModel.kt | 93 +++++++++++++ .../layout/fragment_deactivate_account.xml | 116 ++++++++++++++++ .../main/res/xml/vector_settings_general.xml | 9 +- 17 files changed, 551 insertions(+), 28 deletions(-) create mode 100644 matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountParams.kt create mode 100644 matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountTask.kt create mode 100644 vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountFragment.kt create mode 100644 vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewEvents.kt create mode 100644 vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewModel.kt create mode 100644 vector/src/main/res/layout/fragment_deactivate_account.xml diff --git a/CHANGES.md b/CHANGES.md index 0c1d209f61..f43294ca9f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -7,6 +7,7 @@ Features ✨: - Cross-Signing | Verify new session from existing session (#1134) - Cross-Signing | Bootstraping cross signing with 4S from mobile (#985) - Save media files to Gallery (#973) + - Account deactivation (with password only) (#35) Improvements 🙌: - Verification DM / Handle concurrent .start after .ready (#794) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/account/AccountService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/account/AccountService.kt index 68643ff723..ddbaaea6ef 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/account/AccountService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/account/AccountService.kt @@ -23,11 +23,28 @@ import im.vector.matrix.android.api.util.Cancelable * This interface defines methods to manage the account. It's implemented at the session level. */ interface AccountService { - /** * Ask the homeserver to change the password. * @param password Current password. * @param newPassword New password */ fun changePassword(password: String, newPassword: String, callback: MatrixCallback): Cancelable + + /** + * Deactivate the account. + * + * This will make your account permanently unusable. You will not be able to log in, and no one will be able to re-register + * the same user ID. This will cause your account to leave all rooms it is participating in, and it will remove your account + * details from your identity server. This action is irreversible.\n\nDeactivating your account does not by default + * cause us to forget messages you have sent. If you would like us to forget your messages, please tick the box below. + * + * Message visibility in Matrix is similar to email. Our forgetting your messages means that messages you have sent will not + * be shared with any new or unregistered users, but registered users who already have access to these messages will still + * have access to their copy. + * + * @param password the account password + * @param eraseAllData set to true to forget all messages that have been sent. Warning: this will cause future users to see + * an incomplete view of conversations + */ + fun deactivateAccount(password: String, eraseAllData: Boolean, callback: MatrixCallback): Cancelable } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountAPI.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountAPI.kt index 23d8210e89..e7fbd3748c 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountAPI.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountAPI.kt @@ -30,4 +30,12 @@ internal interface AccountAPI { */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "account/password") fun changePassword(@Body params: ChangePasswordParams): Call + + /** + * Deactivate the user account + * + * @param params the deactivate account params + */ + @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "account/deactivate") + fun deactivate(@Body params: DeactivateAccountParams): Call } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountModule.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountModule.kt index 87e003b0d3..032139ce5d 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountModule.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountModule.kt @@ -39,6 +39,9 @@ internal abstract class AccountModule { @Binds abstract fun bindChangePasswordTask(task: DefaultChangePasswordTask): ChangePasswordTask + @Binds + abstract fun bindDeactivateAccountTask(task: DefaultDeactivateAccountTask): DeactivateAccountTask + @Binds abstract fun bindAccountService(service: DefaultAccountService): AccountService } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountParams.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountParams.kt new file mode 100644 index 0000000000..7a099ca03d --- /dev/null +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountParams.kt @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2020 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 im.vector.matrix.android.internal.session.account; + +import com.squareup.moshi.Json; +import com.squareup.moshi.JsonClass; +import im.vector.matrix.android.internal.crypto.model.rest.UserPasswordAuth + +@JsonClass(generateAdapter = true) +internal data class DeactivateAccountParams( + @Json(name = "auth") + val auth: UserPasswordAuth? = null, + + // Set to true to erase all data of the account + @Json(name = "erase") + val erase: Boolean +) { + companion object { + fun create(userId: String, password: String, erase: Boolean): DeactivateAccountParams { + return DeactivateAccountParams( + auth = UserPasswordAuth(user = userId, password = password), + erase = erase + ) + } + } +} diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountTask.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountTask.kt new file mode 100644 index 0000000000..b8b57a24a4 --- /dev/null +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountTask.kt @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2020 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 im.vector.matrix.android.internal.session.account + +import im.vector.matrix.android.api.failure.Failure +import im.vector.matrix.android.internal.auth.registration.RegistrationFlowResponse +import im.vector.matrix.android.internal.di.MoshiProvider +import im.vector.matrix.android.internal.di.UserId +import im.vector.matrix.android.internal.network.executeRequest +import im.vector.matrix.android.internal.task.Task +import org.greenrobot.eventbus.EventBus +import javax.inject.Inject + +internal interface DeactivateAccountTask : Task { + data class Params( + val password: String, + val eraseAllData: Boolean + ) +} + +internal class DefaultDeactivateAccountTask @Inject constructor( + private val accountAPI: AccountAPI, + private val eventBus: EventBus, + @UserId private val userId: String +) : DeactivateAccountTask { + + override suspend fun execute(params: DeactivateAccountTask.Params) { + val deactivateAccountParams = DeactivateAccountParams.create(userId, params.password, params.eraseAllData) + try { + executeRequest(eventBus) { + apiCall = accountAPI.deactivate(deactivateAccountParams) + } + } catch (throwable: Throwable) { + if (throwable is Failure.OtherServerError + && throwable.httpCode == 401 + /* Avoid infinite loop */ + && deactivateAccountParams.auth?.session == null) { + try { + MoshiProvider.providesMoshi() + .adapter(RegistrationFlowResponse::class.java) + .fromJson(throwable.errorBody) + } catch (e: Exception) { + null + }?.let { + // Retry with authentication + try { + executeRequest(eventBus) { + apiCall = accountAPI.deactivate( + deactivateAccountParams.copy(auth = deactivateAccountParams.auth?.copy(session = it.session)) + ) + } + return + } catch (failure: Throwable) { + throw failure + } + } + } + throw throwable + } + + // TODO This task should also do the cleanup + } +} diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DefaultAccountService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DefaultAccountService.kt index fce01994d3..f6db1dd3db 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DefaultAccountService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DefaultAccountService.kt @@ -24,6 +24,7 @@ import im.vector.matrix.android.internal.task.configureWith import javax.inject.Inject internal class DefaultAccountService @Inject constructor(private val changePasswordTask: ChangePasswordTask, + private val deactivateAccountTask: DeactivateAccountTask, private val taskExecutor: TaskExecutor) : AccountService { override fun changePassword(password: String, newPassword: String, callback: MatrixCallback): Cancelable { @@ -33,4 +34,12 @@ internal class DefaultAccountService @Inject constructor(private val changePassw } .executeBy(taskExecutor) } + + override fun deactivateAccount(password: String, eraseAllData: Boolean, callback: MatrixCallback): Cancelable { + return deactivateAccountTask + .configureWith(DeactivateAccountTask.Params(password, eraseAllData)) { + this.callback = callback + } + .executeBy(taskExecutor) + } } diff --git a/vector/src/main/java/im/vector/riotx/core/di/FragmentModule.kt b/vector/src/main/java/im/vector/riotx/core/di/FragmentModule.kt index c2f2959bd7..d22d80c4b3 100644 --- a/vector/src/main/java/im/vector/riotx/core/di/FragmentModule.kt +++ b/vector/src/main/java/im/vector/riotx/core/di/FragmentModule.kt @@ -81,6 +81,7 @@ import im.vector.riotx.features.settings.VectorSettingsNotificationPreferenceFra import im.vector.riotx.features.settings.VectorSettingsNotificationsTroubleshootFragment import im.vector.riotx.features.settings.VectorSettingsPreferencesFragment import im.vector.riotx.features.settings.VectorSettingsSecurityPrivacyFragment +import im.vector.riotx.features.settings.account.deactivation.DeactivateAccountFragment import im.vector.riotx.features.settings.crosssigning.CrossSigningSettingsFragment import im.vector.riotx.features.settings.devices.VectorSettingsDevicesFragment import im.vector.riotx.features.settings.devtools.AccountDataFragment @@ -445,8 +446,14 @@ interface FragmentModule { @IntoMap @FragmentKey(BootstrapAccountPasswordFragment::class) fun bindBootstrapAccountPasswordFragment(fragment: BootstrapAccountPasswordFragment): Fragment + @Binds @IntoMap @FragmentKey(BootstrapMigrateBackupFragment::class) fun bindBootstrapMigrateBackupFragment(fragment: BootstrapMigrateBackupFragment): Fragment + + @Binds + @IntoMap + @FragmentKey(DeactivateAccountFragment::class) + fun bindDeactivateAccountFragment(fragment: DeactivateAccountFragment): Fragment } diff --git a/vector/src/main/java/im/vector/riotx/features/MainActivity.kt b/vector/src/main/java/im/vector/riotx/features/MainActivity.kt index bc5a1aff95..9c5569f66d 100644 --- a/vector/src/main/java/im/vector/riotx/features/MainActivity.kt +++ b/vector/src/main/java/im/vector/riotx/features/MainActivity.kt @@ -49,6 +49,7 @@ data class MainActivityArgs( val clearCache: Boolean = false, val clearCredentials: Boolean = false, val isUserLoggedOut: Boolean = false, + val isAccountDeactivated: Boolean = false, val isSoftLogout: Boolean = false ) : Parcelable @@ -110,6 +111,7 @@ class MainActivity : VectorBaseActivity() { clearCache = argsFromIntent?.clearCache ?: false, clearCredentials = argsFromIntent?.clearCredentials ?: false, isUserLoggedOut = argsFromIntent?.isUserLoggedOut ?: false, + isAccountDeactivated = argsFromIntent?.isAccountDeactivated ?: false, isSoftLogout = argsFromIntent?.isSoftLogout ?: false ) } @@ -122,7 +124,7 @@ class MainActivity : VectorBaseActivity() { } when { args.clearCredentials -> session.signOut( - !args.isUserLoggedOut, + !args.isUserLoggedOut && !args.isAccountDeactivated, object : MatrixCallback { override fun onSuccess(data: Unit) { Timber.w("SIGN_OUT: success, start app") @@ -182,16 +184,16 @@ class MainActivity : VectorBaseActivity() { private fun startNextActivityAndFinish() { val intent = when { args.clearCredentials - && !args.isUserLoggedOut -> - // User has explicitly asked to log out + && (!args.isUserLoggedOut || args.isAccountDeactivated) -> + // User has explicitly asked to log out or deactivated his account LoginActivity.newIntent(this, null) - args.isSoftLogout -> + args.isSoftLogout -> // The homeserver has invalidated the token, with a soft logout SoftLogoutActivity.newIntent(this) - args.isUserLoggedOut -> + args.isUserLoggedOut -> // the homeserver has invalidated the token (password changed, device deleted, other security reasons) SignedOutActivity.newIntent(this) - sessionHolder.hasActiveSession() -> + sessionHolder.hasActiveSession() -> // We have a session. // Check it can be opened if (sessionHolder.getActiveSession().isOpenable) { @@ -200,7 +202,7 @@ class MainActivity : VectorBaseActivity() { // The token is still invalid SoftLogoutActivity.newIntent(this) } - else -> + else -> // First start, or no active session LoginActivity.newIntent(this, null) } diff --git a/vector/src/main/java/im/vector/riotx/features/settings/VectorPreferences.kt b/vector/src/main/java/im/vector/riotx/features/settings/VectorPreferences.kt index f0a5a8ace8..e765f961dd 100755 --- a/vector/src/main/java/im/vector/riotx/features/settings/VectorPreferences.kt +++ b/vector/src/main/java/im/vector/riotx/features/settings/VectorPreferences.kt @@ -159,7 +159,6 @@ class VectorPreferences @Inject constructor(private val context: Context) { private const val DID_ASK_TO_IGNORE_BATTERY_OPTIMIZATIONS_KEY = "DID_ASK_TO_IGNORE_BATTERY_OPTIMIZATIONS_KEY" private const val DID_MIGRATE_TO_NOTIFICATION_REWORK = "DID_MIGRATE_TO_NOTIFICATION_REWORK" private const val DID_ASK_TO_USE_ANALYTICS_TRACKING_KEY = "DID_ASK_TO_USE_ANALYTICS_TRACKING_KEY" - const val SETTINGS_DEACTIVATE_ACCOUNT_KEY = "SETTINGS_DEACTIVATE_ACCOUNT_KEY" private const val SETTINGS_DISPLAY_ALL_EVENTS_KEY = "SETTINGS_DISPLAY_ALL_EVENTS_KEY" private const val MEDIA_SAVING_3_DAYS = 0 diff --git a/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsActivity.kt b/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsActivity.kt index 5db14fdbd2..6d00f02c97 100755 --- a/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsActivity.kt +++ b/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsActivity.kt @@ -20,6 +20,7 @@ import android.content.Intent import androidx.fragment.app.FragmentManager import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat +import im.vector.matrix.android.api.failure.GlobalError import im.vector.matrix.android.api.session.Session import im.vector.riotx.R import im.vector.riotx.core.di.ScreenComponent @@ -43,6 +44,8 @@ class VectorSettingsActivity : VectorBaseActivity(), private var keyToHighlight: String? = null + var ignoreInvalidTokenError = false + @Inject lateinit var session: Session override fun injectWith(injector: ScreenComponent) { @@ -57,7 +60,7 @@ class VectorSettingsActivity : VectorBaseActivity(), when (intent.getIntExtra(EXTRA_DIRECT_ACCESS, EXTRA_DIRECT_ACCESS_ROOT)) { EXTRA_DIRECT_ACCESS_ADVANCED_SETTINGS -> replaceFragment(R.id.vector_settings_page, VectorSettingsAdvancedSettingsFragment::class.java, null, FRAGMENT_TAG) - EXTRA_DIRECT_ACCESS_SECURITY_PRIVACY -> + EXTRA_DIRECT_ACCESS_SECURITY_PRIVACY -> replaceFragment(R.id.vector_settings_page, VectorSettingsSecurityPrivacyFragment::class.java, null, FRAGMENT_TAG) else -> replaceFragment(R.id.vector_settings_page, VectorSettingsRootFragment::class.java, null, FRAGMENT_TAG) @@ -110,6 +113,14 @@ class VectorSettingsActivity : VectorBaseActivity(), return keyToHighlight } + override fun handleInvalidToken(globalError: GlobalError.InvalidToken) { + if (ignoreInvalidTokenError) { + Timber.w("Ignoring invalid token global error") + } else { + super.handleInvalidToken(globalError) + } + } + companion object { fun getIntent(context: Context, directAccess: Int) = Intent(context, VectorSettingsActivity::class.java) .apply { putExtra(EXTRA_DIRECT_ACCESS, directAccess) } diff --git a/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsGeneralFragment.kt b/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsGeneralFragment.kt index f754064fbc..802cf7b33f 100644 --- a/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsGeneralFragment.kt +++ b/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsGeneralFragment.kt @@ -234,19 +234,6 @@ class VectorSettingsGeneralFragment : VectorSettingsBaseFragment() { false } - - // Deactivate account section - - // deactivate account - findPreference(VectorPreferences.SETTINGS_DEACTIVATE_ACCOUNT_KEY)!! - .onPreferenceClickListener = Preference.OnPreferenceClickListener { - activity?.let { - notImplemented() - // TODO startActivity(DeactivateAccountActivity.getIntent(it)) - } - - false - } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { diff --git a/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountFragment.kt b/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountFragment.kt new file mode 100644 index 0000000000..487d913b7e --- /dev/null +++ b/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountFragment.kt @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2020 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 im.vector.riotx.features.settings.account.deactivation + +import android.content.Context +import android.os.Bundle +import android.view.View +import com.airbnb.mvrx.fragmentViewModel +import com.airbnb.mvrx.withState +import com.jakewharton.rxbinding3.widget.textChanges +import im.vector.riotx.R +import im.vector.riotx.core.extensions.exhaustive +import im.vector.riotx.core.extensions.showPassword +import im.vector.riotx.core.platform.VectorBaseActivity +import im.vector.riotx.core.platform.VectorBaseFragment +import im.vector.riotx.features.MainActivity +import im.vector.riotx.features.MainActivityArgs +import im.vector.riotx.features.settings.VectorSettingsActivity +import kotlinx.android.synthetic.main.fragment_deactivate_account.* +import javax.inject.Inject + +class DeactivateAccountFragment @Inject constructor( + val viewModelFactory: DeactivateAccountViewModel.Factory +) : VectorBaseFragment() { + + private val viewModel: DeactivateAccountViewModel by fragmentViewModel() + + override fun getLayoutResId() = R.layout.fragment_deactivate_account + + override fun onResume() { + super.onResume() + (activity as? VectorBaseActivity)?.supportActionBar?.setTitle(R.string.deactivate_account_title) + } + + private var settingsActivity: VectorSettingsActivity? = null + + override fun onAttach(context: Context) { + super.onAttach(context) + settingsActivity = context as? VectorSettingsActivity + } + + override fun onDetach() { + super.onDetach() + settingsActivity = null + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + setupUi() + setupViewListeners() + observeViewEvents() + } + + private fun setupUi() { + deactivateAccountPassword.textChanges() + .subscribe { + deactivateAccountPasswordTil.error = null + deactivateAccountSubmit.isEnabled = it.isNotBlank() + } + .disposeOnDestroyView() + } + + private fun setupViewListeners() { + deactivateAccountPasswordReveal.setOnClickListener { + viewModel.handle(DeactivateAccountAction.TogglePassword) + } + + deactivateAccountCancel.setOnClickListener { + (activity as? VectorBaseActivity)?.onBackPressed() + } + + deactivateAccountSubmit.setOnClickListener { + viewModel.handle(DeactivateAccountAction.DeactivateAccount( + deactivateAccountPassword.text.toString(), + deactivateAccountEraseCheckbox.isChecked)) + } + } + + private fun observeViewEvents() { + viewModel.observeViewEvents { + when (it) { + is DeactivateAccountViewEvents.Loading -> { + settingsActivity?.ignoreInvalidTokenError = true + showLoadingDialog(it.message) + } + DeactivateAccountViewEvents.EmptyPassword -> { + settingsActivity?.ignoreInvalidTokenError = false + deactivateAccountPasswordTil.error = getString(R.string.error_empty_field_your_password) + } + DeactivateAccountViewEvents.InvalidPassword -> { + settingsActivity?.ignoreInvalidTokenError = false + deactivateAccountPasswordTil.error = getString(R.string.settings_fail_to_update_password_invalid_current_password) + } + is DeactivateAccountViewEvents.OtherFailure -> { + settingsActivity?.ignoreInvalidTokenError = false + displayErrorDialog(it.throwable) + } + DeactivateAccountViewEvents.Done -> + MainActivity.restartApp(activity!!, MainActivityArgs(clearCredentials = true, isAccountDeactivated = true)) + + }.exhaustive + } + } + + override fun invalidate() = withState(viewModel) { state -> + deactivateAccountPassword.showPassword(state.passwordShown) + deactivateAccountPasswordReveal.setImageResource(if (state.passwordShown) R.drawable.ic_eye_closed_black else R.drawable.ic_eye_black) + } +} diff --git a/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewEvents.kt b/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewEvents.kt new file mode 100644 index 0000000000..4e7f7252e2 --- /dev/null +++ b/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewEvents.kt @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2020 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 im.vector.riotx.features.settings.account.deactivation + +import im.vector.riotx.core.platform.VectorViewEvents + +/** + * Transient events for deactivate account settings screen + */ +sealed class DeactivateAccountViewEvents : VectorViewEvents { + data class Loading(val message: CharSequence? = null) : DeactivateAccountViewEvents() + object EmptyPassword : DeactivateAccountViewEvents() + object InvalidPassword : DeactivateAccountViewEvents() + data class OtherFailure(val throwable: Throwable) : DeactivateAccountViewEvents() + object Done : DeactivateAccountViewEvents() +} diff --git a/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewModel.kt b/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewModel.kt new file mode 100644 index 0000000000..adfc9ff5ae --- /dev/null +++ b/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewModel.kt @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2020 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 im.vector.riotx.features.settings.account.deactivation + +import com.airbnb.mvrx.FragmentViewModelContext +import com.airbnb.mvrx.MvRxState +import com.airbnb.mvrx.MvRxViewModelFactory +import com.airbnb.mvrx.ViewModelContext +import com.squareup.inject.assisted.Assisted +import com.squareup.inject.assisted.AssistedInject +import im.vector.matrix.android.api.MatrixCallback +import im.vector.matrix.android.api.failure.isInvalidPassword +import im.vector.matrix.android.api.session.Session +import im.vector.riotx.core.extensions.exhaustive +import im.vector.riotx.core.platform.VectorViewModel +import im.vector.riotx.core.platform.VectorViewModelAction + +data class DeactivateAccountViewState( + val passwordShown: Boolean = false +) : MvRxState + +sealed class DeactivateAccountAction : VectorViewModelAction { + object TogglePassword : DeactivateAccountAction() + data class DeactivateAccount(val password: String, val eraseAllData: Boolean) : DeactivateAccountAction() +} + +class DeactivateAccountViewModel @AssistedInject constructor(@Assisted private val initialState: DeactivateAccountViewState, + private val session: Session) + : VectorViewModel(initialState) { + + @AssistedInject.Factory + interface Factory { + fun create(initialState: DeactivateAccountViewState): DeactivateAccountViewModel + } + + override fun handle(action: DeactivateAccountAction) { + when (action) { + DeactivateAccountAction.TogglePassword -> handleTogglePassword() + is DeactivateAccountAction.DeactivateAccount -> handleDeactivateAccount(action) + }.exhaustive + } + + private fun handleTogglePassword() = withState { + setState { + copy(passwordShown = !passwordShown) + } + } + + private fun handleDeactivateAccount(action: DeactivateAccountAction.DeactivateAccount) { + if (action.password.isEmpty()) { + _viewEvents.post(DeactivateAccountViewEvents.EmptyPassword) + return + } + + _viewEvents.post(DeactivateAccountViewEvents.Loading()) + + session.deactivateAccount(action.password, action.eraseAllData, object : MatrixCallback { + override fun onSuccess(data: Unit) { + _viewEvents.post(DeactivateAccountViewEvents.Done) + } + + override fun onFailure(failure: Throwable) { + if (failure.isInvalidPassword()) { + _viewEvents.post(DeactivateAccountViewEvents.InvalidPassword) + } else { + _viewEvents.post(DeactivateAccountViewEvents.OtherFailure(failure)) + } + } + }) + } + + companion object : MvRxViewModelFactory { + + @JvmStatic + override fun create(viewModelContext: ViewModelContext, state: DeactivateAccountViewState): DeactivateAccountViewModel? { + val fragment: DeactivateAccountFragment = (viewModelContext as FragmentViewModelContext).fragment() + return fragment.viewModelFactory.create(state) + } + } +} diff --git a/vector/src/main/res/layout/fragment_deactivate_account.xml b/vector/src/main/res/layout/fragment_deactivate_account.xml new file mode 100644 index 0000000000..aca8adf12d --- /dev/null +++ b/vector/src/main/res/layout/fragment_deactivate_account.xml @@ -0,0 +1,116 @@ + + + + + + + + + + + + + + + + + + + + + + + + +