Merge pull request #4091 from vector-im/feature/adm/verify-exported-keys-output

Verify exported keys output
This commit is contained in:
Benoit Marty 2021-09-28 15:14:34 +02:00 committed by GitHub
commit 23615c0038
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 263 additions and 4 deletions

1
changelog.d/4082.bugfix Normal file
View File

@ -0,0 +1 @@
Verifying exported E2E keys to provide user feedback when the output is malformed

View File

@ -314,6 +314,11 @@ android {
} }
} }
configurations {
// videocache includes a sl4j logger which causes mockk to attempt to call the static android Log
testImplementation.exclude group: 'org.slf4j', module: 'slf4j-android'
}
dependencies { dependencies {
implementation project(":matrix-sdk-android") implementation project(":matrix-sdk-android")
@ -490,6 +495,7 @@ dependencies {
// TESTS // TESTS
testImplementation libs.tests.junit testImplementation libs.tests.junit
testImplementation libs.tests.kluent testImplementation libs.tests.kluent
testImplementation libs.mockk.mockk
// Plant Timber tree for test // Plant Timber tree for test
testImplementation libs.tests.timberJunitRule testImplementation libs.tests.timberJunitRule

View File

@ -26,6 +26,7 @@ import im.vector.app.EmojiCompatFontProvider
import im.vector.app.EmojiCompatWrapper import im.vector.app.EmojiCompatWrapper
import im.vector.app.VectorApplication import im.vector.app.VectorApplication
import im.vector.app.core.dialogs.UnrecognizedCertificateDialog import im.vector.app.core.dialogs.UnrecognizedCertificateDialog
import im.vector.app.core.dispatchers.CoroutineDispatchers
import im.vector.app.core.error.ErrorFormatter import im.vector.app.core.error.ErrorFormatter
import im.vector.app.core.network.WifiDetector import im.vector.app.core.network.WifiDetector
import im.vector.app.core.pushers.PushersManager import im.vector.app.core.pushers.PushersManager
@ -171,6 +172,8 @@ interface VectorComponent {
fun appCoroutineScope(): CoroutineScope fun appCoroutineScope(): CoroutineScope
fun coroutineDispatchers(): CoroutineDispatchers
fun jitsiActiveConferenceHolder(): JitsiActiveConferenceHolder fun jitsiActiveConferenceHolder(): JitsiActiveConferenceHolder
@Component.Factory @Component.Factory

View File

@ -23,6 +23,7 @@ import android.content.res.Resources
import dagger.Binds import dagger.Binds
import dagger.Module import dagger.Module
import dagger.Provides import dagger.Provides
import im.vector.app.core.dispatchers.CoroutineDispatchers
import im.vector.app.core.error.DefaultErrorFormatter import im.vector.app.core.error.DefaultErrorFormatter
import im.vector.app.core.error.ErrorFormatter import im.vector.app.core.error.ErrorFormatter
import im.vector.app.features.invite.AutoAcceptInvites import im.vector.app.features.invite.AutoAcceptInvites
@ -105,6 +106,12 @@ abstract class VectorModule {
fun providesApplicationCoroutineScope(): CoroutineScope { fun providesApplicationCoroutineScope(): CoroutineScope {
return CoroutineScope(SupervisorJob() + Dispatchers.Main) return CoroutineScope(SupervisorJob() + Dispatchers.Main)
} }
@Provides
@JvmStatic
fun providesCoroutineDispatchers(): CoroutineDispatchers {
return CoroutineDispatchers(io = Dispatchers.IO)
}
} }
@Binds @Binds

View File

@ -0,0 +1,22 @@
/*
* Copyright (c) 2021 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.app.core.dispatchers
import kotlinx.coroutines.CoroutineDispatcher
import javax.inject.Inject
data class CoroutineDispatchers @Inject constructor(val io: CoroutineDispatcher)

View File

@ -18,24 +18,43 @@ package im.vector.app.features.crypto.keys
import android.content.Context import android.content.Context
import android.net.Uri import android.net.Uri
import kotlinx.coroutines.Dispatchers import im.vector.app.core.dispatchers.CoroutineDispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.Session
import javax.inject.Inject import javax.inject.Inject
class KeysExporter @Inject constructor( class KeysExporter @Inject constructor(
private val session: Session, private val session: Session,
private val context: Context private val context: Context,
private val dispatchers: CoroutineDispatchers
) { ) {
/** /**
* Export keys and write them to the provided uri * Export keys and write them to the provided uri
*/ */
suspend fun export(password: String, uri: Uri) { suspend fun export(password: String, uri: Uri) {
return withContext(Dispatchers.IO) { withContext(dispatchers.io) {
val data = session.cryptoService().exportRoomKeys(password) val data = session.cryptoService().exportRoomKeys(password)
context.contentResolver.openOutputStream(uri) context.contentResolver.openOutputStream(uri)
?.use { it.write(data) } ?.use { it.write(data) }
?: throw IllegalStateException("Unable to open file for writting") ?: throw IllegalStateException("Unable to open file for writing")
verifyExportedKeysOutputFileSize(uri, expectedSize = data.size.toLong())
}
}
private fun verifyExportedKeysOutputFileSize(uri: Uri, expectedSize: Long) {
val output = context.contentResolver.openFileDescriptor(uri, "r", null)
when {
output == null -> throw IllegalStateException("Exported file not found")
output.statSize != expectedSize -> {
throw UnexpectedExportKeysFileSizeException(
expectedFileSize = expectedSize,
actualFileSize = output.statSize
)
}
} }
} }
} }
class UnexpectedExportKeysFileSizeException(expectedFileSize: Long, actualFileSize: Long) : IllegalStateException(
"Exported Keys file has unexpected file size, got: $actualFileSize but expected: $expectedFileSize"
)

View File

@ -0,0 +1,97 @@
/*
* Copyright (c) 2021 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.app.features.crypto.keys
import android.net.Uri
import android.os.ParcelFileDescriptor
import im.vector.app.core.dispatchers.CoroutineDispatchers
import im.vector.app.test.fakes.FakeContext
import im.vector.app.test.fakes.FakeCryptoService
import im.vector.app.test.fakes.FakeSession
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import org.amshove.kluent.internal.assertFailsWith
import org.junit.Before
import org.junit.Test
private val A_URI = mockk<Uri>()
private val A_ROOM_KEYS_EXPORT = ByteArray(size = 111)
private const val A_PASSWORD = "a password"
class KeysExporterTest {
private val cryptoService = FakeCryptoService()
private val context = FakeContext()
private val keysExporter = KeysExporter(
session = FakeSession(cryptoService = cryptoService),
context = context.instance,
dispatchers = CoroutineDispatchers(Dispatchers.Unconfined)
)
@Before
fun setUp() {
cryptoService.roomKeysExport = A_ROOM_KEYS_EXPORT
}
@Test
fun `when exporting then writes exported keys to context output stream`() {
givenFileDescriptorWithSize(size = A_ROOM_KEYS_EXPORT.size.toLong())
val outputStream = context.givenOutputStreamFor(A_URI)
runBlocking { keysExporter.export(A_PASSWORD, A_URI) }
verify { outputStream.write(A_ROOM_KEYS_EXPORT) }
}
@Test
fun `given different file size returned for export when exporting then throws UnexpectedExportKeysFileSizeException`() {
givenFileDescriptorWithSize(size = 110)
context.givenOutputStreamFor(A_URI)
assertFailsWith<UnexpectedExportKeysFileSizeException> {
runBlocking { keysExporter.export(A_PASSWORD, A_URI) }
}
}
@Test
fun `given output stream is unavailable for exporting to when exporting then throws IllegalStateException`() {
context.givenMissingOutputStreamFor(A_URI)
assertFailsWith<IllegalStateException>(message = "Unable to open file for writing") {
runBlocking { keysExporter.export(A_PASSWORD, A_URI) }
}
}
@Test
fun `given exported file is missing after export when exporting then throws IllegalStateException`() {
context.givenFileDescriptor(A_URI, mode = "r") { null }
context.givenOutputStreamFor(A_URI)
assertFailsWith<IllegalStateException>(message = "Exported file not found") {
runBlocking { keysExporter.export(A_PASSWORD, A_URI) }
}
}
private fun givenFileDescriptorWithSize(size: Long) {
context.givenFileDescriptor(A_URI, mode = "r") {
mockk<ParcelFileDescriptor>().also { every { it.statSize } returns size }
}
}
}

View File

@ -0,0 +1,50 @@
/*
* Copyright (c) 2021 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.app.test.fakes
import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.os.ParcelFileDescriptor
import io.mockk.every
import io.mockk.mockk
import java.io.OutputStream
class FakeContext {
private val contentResolver = mockk<ContentResolver>()
val instance = mockk<Context>()
init {
every { instance.contentResolver } returns contentResolver
}
fun givenFileDescriptor(uri: Uri, mode: String, factory: () -> ParcelFileDescriptor?) {
val fileDescriptor = factory()
every { contentResolver.openFileDescriptor(uri, mode, null) } returns fileDescriptor
}
fun givenOutputStreamFor(uri: Uri): OutputStream {
val outputStream = mockk<OutputStream>(relaxed = true)
every { contentResolver.openOutputStream(uri) } returns outputStream
return outputStream
}
fun givenMissingOutputStreamFor(uri: Uri) {
every { contentResolver.openOutputStream(uri) } returns null
}
}

View File

@ -0,0 +1,27 @@
/*
* Copyright (c) 2021 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.app.test.fakes
import io.mockk.mockk
import org.matrix.android.sdk.api.session.crypto.CryptoService
class FakeCryptoService : CryptoService by mockk() {
var roomKeysExport = ByteArray(size = 1)
override suspend fun exportRoomKeys(password: String) = roomKeysExport
}

View File

@ -0,0 +1,27 @@
/*
* Copyright (c) 2021 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.app.test.fakes
import io.mockk.mockk
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.crypto.CryptoService
class FakeSession(
private val cryptoService: CryptoService = FakeCryptoService()
) : Session by mockk(relaxed = true) {
override fun cryptoService() = cryptoService
}