-
Notifications
You must be signed in to change notification settings - Fork 742
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature/unwedging #1261
Merged
Merged
Feature/unwedging #1261
Changes from 16 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
a8641ef
Split KeysBackup to several files. No other change.
bmarty 41a8f40
Improve API
bmarty 0cb43ee
Add test for Unwedging (before implementing it)
bmarty 00c239b
cleanup
bmarty 5900245
Make the test fail before unwedging implementation
bmarty 7924ef2
Add Javadoc
bmarty a42eb42
Avoid injecting Credentials
bmarty 13cd13a
Create RoomEncryptorsStore
bmarty 6186c22
improve code
bmarty 4d296dd
Avoid injecting credentials
bmarty f989eed
Use @Throws(MXCryptoError::class)
bmarty 91cf4b6
var -> val
bmarty ddb00ba
Enable Timber log in integration tests
bmarty 3615ca6
VersionName can be null when running integration test
bmarty a6368c4
Restart broken Olm sessions ([MSC1719](https://github.com/matrix-org/…
bmarty 9b320ed
Fix unwedging
BillCarsonFr d0f776a
Discard session command only encrypted room
BillCarsonFr e37dd54
code review
BillCarsonFr 4ee13b6
Merge branch 'develop' into feature/unwedging
bmarty File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
248 changes: 248 additions & 0 deletions
248
...dk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,248 @@ | ||
/* | ||
* 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.extensions.tryThis | ||
import im.vector.matrix.android.api.session.crypto.MXCryptoError | ||
import im.vector.matrix.android.api.session.events.model.EventType | ||
import im.vector.matrix.android.api.session.events.model.toModel | ||
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 im.vector.matrix.android.common.TestConstants | ||
import im.vector.matrix.android.internal.crypto.model.OlmSessionWrapper | ||
import im.vector.matrix.android.internal.crypto.model.event.EncryptedEventContent | ||
import im.vector.matrix.android.internal.crypto.model.rest.UserPasswordAuth | ||
import im.vector.matrix.android.internal.crypto.store.db.deserializeFromRealm | ||
import im.vector.matrix.android.internal.crypto.store.db.serializeForRealm | ||
import org.amshove.kluent.shouldBe | ||
import org.junit.Assert | ||
import org.junit.Before | ||
import org.junit.FixMethodOrder | ||
import org.junit.Test | ||
import org.junit.runner.RunWith | ||
import org.junit.runners.MethodSorters | ||
import org.matrix.olm.OlmSession | ||
import timber.log.Timber | ||
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<TimelineEvent> | ||
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() | ||
|
||
val bobFinalLatch = CountDownLatch(1) | ||
val bobHasThreeDecryptedEventsListener = object : Timeline.Listener { | ||
override fun onTimelineFailure(throwable: Throwable) { | ||
// noop | ||
} | ||
|
||
override fun onNewTimelineEvents(eventIds: List<String>) { | ||
// noop | ||
} | ||
|
||
override fun onTimelineUpdated(snapshot: List<TimelineEvent>) { | ||
val decryptedEventReceivedByBob = snapshot.filter { it.root.type == EventType.ENCRYPTED } | ||
Timber.d("Bob can now decrypt ${decryptedEventReceivedByBob.size} messages") | ||
if (decryptedEventReceivedByBob.size == 3) { | ||
if (decryptedEventReceivedByBob[0].root.mCryptoError == MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID) { | ||
bobFinalLatch.countDown() | ||
} | ||
} | ||
} | ||
} | ||
bobTimeline.addListener(bobHasThreeDecryptedEventsListener) | ||
|
||
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 | ||
val firstMessageSession = messagesReceivedByBob[0].root.content.toModel<EncryptedEventContent>()!!.sessionId!! | ||
|
||
// - 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()!!)!! | ||
|
||
val oldSession = serializeForRealm(olmSession.olmSession) | ||
|
||
aliceSession.cryptoService().discardOutbundSession(roomFromAlicePOV.roomId) | ||
Thread.sleep(6_000) | ||
|
||
latch = CountDownLatch(1) | ||
bobEventsListener = createEventListener(latch, 2) | ||
bobTimeline.addListener(bobEventsListener) | ||
messagesReceivedByBob = emptyList() | ||
|
||
Timber.i("## CRYPTO | testUnwedging: Alice sends a 2nd message with a 2nd megolm session") | ||
// - 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 | ||
// Session should have changed | ||
val secondMessageSession = messagesReceivedByBob[0].root.content.toModel<EncryptedEventContent>()!!.sessionId!! | ||
Assert.assertNotEquals(firstMessageSession, secondMessageSession) | ||
|
||
// Let us wedge the session now. Set crypto state like after the first message | ||
Timber.i("## CRYPTO | testUnwedging: wedge the session now. Set crypto state like after the first message") | ||
|
||
aliceCryptoStore.storeSession(OlmSessionWrapper(deserializeFromRealm<OlmSession>(oldSession)!!), bobSession.cryptoService().getMyDevice().identityKey()!!) | ||
Thread.sleep(6_000) | ||
|
||
// Force new session, and key share | ||
aliceSession.cryptoService().discardOutbundSession(roomFromAlicePOV.roomId) | ||
|
||
// Wait for the message to be received by Bob | ||
mTestHelper.waitWithLatch { | ||
bobEventsListener = createEventListener(it, 3) | ||
bobTimeline.addListener(bobEventsListener) | ||
messagesReceivedByBob = emptyList() | ||
|
||
Timber.i("## CRYPTO | testUnwedging: Alice sends a 3rd message with a 3rd megolm session but a wedged olm session") | ||
// - Alice sends a 3rd message with a 3rd megolm session but a wedged olm session | ||
roomFromAlicePOV.sendTextMessage("Third message") | ||
// Bob should not be able to decrypt, because the session key could not be sent | ||
} | ||
bobTimeline.removeListener(bobEventsListener) | ||
|
||
messagesReceivedByBob.size shouldBe 3 | ||
|
||
val thirdMessageSession = messagesReceivedByBob[0].root.content.toModel<EncryptedEventContent>()!!.sessionId!! | ||
Timber.i("## CRYPTO | testUnwedging: third message session ID $thirdMessageSession") | ||
Assert.assertNotEquals(secondMessageSession, thirdMessageSession) | ||
|
||
Assert.assertEquals(EventType.ENCRYPTED, messagesReceivedByBob[0].root.getClearType()) | ||
Assert.assertEquals(EventType.MESSAGE, messagesReceivedByBob[1].root.getClearType()) | ||
Assert.assertEquals(EventType.MESSAGE, messagesReceivedByBob[2].root.getClearType()) | ||
// Bob Should not be able to decrypt last message, because session could not be sent as the olm channel was wedged | ||
mTestHelper.await(bobFinalLatch) | ||
bobTimeline.removeListener(bobHasThreeDecryptedEventsListener) | ||
|
||
// It's a trick to force key request on fail to decrypt | ||
mTestHelper.doSync<Unit> { | ||
bobSession.cryptoService().crossSigningService() | ||
.initializeCrossSigning(UserPasswordAuth( | ||
user = bobSession.myUserId, | ||
password = TestConstants.PASSWORD | ||
), it) | ||
} | ||
|
||
// Wait until we received back the key | ||
mTestHelper.waitWithLatch { | ||
mTestHelper.retryPeriodicallyWithLatch(it) { | ||
// we should get back the key and be able to decrypt | ||
val result = tryThis { | ||
bobSession.cryptoService().decryptEvent(messagesReceivedByBob[0].root, "") | ||
} | ||
Timber.i("## CRYPTO | testUnwedging: decrypt result ${result?.clearEvent}") | ||
result != null | ||
} | ||
} | ||
|
||
|
||
bobTimeline.dispose() | ||
|
||
cryptoTestData.cleanUp(mTestHelper) | ||
} | ||
|
||
private fun createEventListener(latch: CountDownLatch, expectedNumberOfMessages: Int): Timeline.Listener { | ||
return object : Timeline.Listener { | ||
override fun onTimelineFailure(throwable: Throwable) { | ||
// noop | ||
} | ||
|
||
override fun onNewTimelineEvents(eventIds: List<String>) { | ||
// noop | ||
} | ||
|
||
override fun onTimelineUpdated(snapshot: List<TimelineEvent>) { | ||
messagesReceivedByBob = snapshot.filter { it.root.type == EventType.ENCRYPTED } | ||
|
||
if (messagesReceivedByBob.size == expectedNumberOfMessages) { | ||
latch.countDown() | ||
} | ||
} | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
\o/