From fe4abbbeefbb11175aab77dd8125c7332a9c08dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 27 Apr 2021 16:33:13 +0200 Subject: [PATCH] crypto: Fix a bunch of linter warnings --- .../internal/crypto/DefaultCryptoService.kt | 77 ++++++++----------- .../android/sdk/internal/crypto/OlmMachine.kt | 42 +++++----- 2 files changed, 52 insertions(+), 67 deletions(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DefaultCryptoService.kt index e957618127..fafd1c465b 100755 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DefaultCryptoService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DefaultCryptoService.kt @@ -160,7 +160,7 @@ internal class DefaultCryptoService @Inject constructor( // Locks for some of our operations private val keyClaimLock: Mutex = Mutex() - private val outgointRequestsLock: Mutex = Mutex() + private val outgoingRequestsLock: Mutex = Mutex() private val roomKeyShareLocks: ConcurrentHashMap = ConcurrentHashMap() // TODO does this need to be concurrent? @@ -182,7 +182,7 @@ internal class DefaultCryptoService @Inject constructor( } } - val gossipingBuffer = mutableListOf() + private val gossipingBuffer = mutableListOf() override fun setDeviceName(deviceId: String, deviceName: String, callback: MatrixCallback) { setDeviceNameTask @@ -217,9 +217,7 @@ internal class DefaultCryptoService @Inject constructor( return if (longFormat) "Rust SDK 0.3" else "0.3" } - override fun getMyDevice(): CryptoDeviceInfo { - return olmMachine!!.ownDevice() - } + override fun getMyDevice(): CryptoDeviceInfo = this.olmMachine!!.ownDevice() override fun fetchDevicesList(callback: MatrixCallback) { getDevicesTask @@ -280,15 +278,6 @@ internal class DefaultCryptoService @Inject constructor( return isStarted.get() } - /** - * Tells if the MXCrypto is starting. - * - * @return true if the crypto is starting - */ - fun isStarting(): Boolean { - return isStarting.get() - } - /** * Start the crypto module. * Device keys will be uploaded, then one time keys if there are not enough on the homeserver @@ -326,10 +315,10 @@ internal class DefaultCryptoService @Inject constructor( try { setRustLogger() - olmMachine = OlmMachine(userId, deviceId!!, dataDir, deviceObserver) + this.olmMachine = OlmMachine(userId, deviceId!!, dataDir, deviceObserver) Timber.v( "## CRYPTO | Successfully started up an Olm machine for " + - "${userId}, ${deviceId}, identity keys: ${olmMachine?.identityKeys()}") + "${userId}, ${deviceId}, identity keys: ${this.olmMachine?.identityKeys()}") } catch (throwable: Throwable) { Timber.v("Failed create an Olm machine: $throwable") } @@ -401,7 +390,7 @@ internal class DefaultCryptoService @Inject constructor( override fun getDeviceInfo(userId: String, deviceId: String?): CryptoDeviceInfo? { return if (userId.isNotEmpty() && !deviceId.isNullOrEmpty()) { runBlocking { - olmMachine?.getDevice(userId, deviceId) + this@DefaultCryptoService.olmMachine?.getDevice(userId, deviceId) } } else { null @@ -410,7 +399,7 @@ internal class DefaultCryptoService @Inject constructor( override fun getCryptoDeviceInfo(userId: String): List { return runBlocking { - olmMachine?.getUserDevices(userId) ?: listOf() + this@DefaultCryptoService.olmMachine?.getUserDevices(userId) ?: listOf() } } @@ -420,7 +409,7 @@ internal class DefaultCryptoService @Inject constructor( override fun getLiveCryptoDeviceInfo(userIds: List): LiveData> { return runBlocking { - olmMachine?.getLiveDevices(userIds) ?: LiveDevice(userIds, deviceObserver) + this@DefaultCryptoService.olmMachine?.getLiveDevices(userIds) ?: LiveDevice(userIds, deviceObserver) } } @@ -561,11 +550,10 @@ internal class DefaultCryptoService @Inject constructor( */ @Throws(MXCryptoError::class) override fun decryptEvent(event: Event, timeline: String): MXEventDecryptionResult { - val decrypted = runBlocking { + + return runBlocking { olmMachine!!.decryptRoomEvent(event) } - - return decrypted } /** @@ -670,22 +658,22 @@ internal class DefaultCryptoService @Inject constructor( deviceChanges: DeviceListResponse?, keyCounts: DeviceOneTimeKeysCountSyncResponse?) { // Decrypt and handle our to-device events - val toDeviceEvents = olmMachine!!.receiveSyncChanges(toDevice, deviceChanges, keyCounts) + val toDeviceEvents = this.olmMachine!!.receiveSyncChanges(toDevice, deviceChanges, keyCounts) // Notify the our listeners about room keys so decryption is retried. if (toDeviceEvents.events != null) { - for (event in toDeviceEvents.events) { + toDeviceEvents.events.forEach { event -> if (event.type == "m.room_key") { - val content = event.getClearContent().toModel() ?: continue + val content = event.getClearContent().toModel() ?: return@forEach - val roomId = content.sessionId ?: continue + val roomId = content.sessionId ?: return@forEach val sessionId = content.sessionId notifyRoomKeyReceival(roomId, sessionId) } else if (event.type == "m.forwarded_room_key") { - val content = event.getClearContent().toModel() ?: continue + val content = event.getClearContent().toModel() ?: return@forEach - val roomId = content.sessionId ?: continue + val roomId = content.sessionId ?: return@forEach val sessionId = content.sessionId notifyRoomKeyReceival(roomId, sessionId) @@ -696,13 +684,14 @@ internal class DefaultCryptoService @Inject constructor( private suspend fun preshareRoomKey(roomId: String, roomMembers: List) { keyClaimLock.withLock { - val request = olmMachine!!.getMissingSessions(roomMembers) + val request = this.olmMachine!!.getMissingSessions(roomMembers) + // This request can only be a keys claim request. if (request != null) { - // This request can only be a keys claim request. when (request) { is Request.KeysClaim -> { claimKeys(request) } + else -> {} } } } @@ -711,7 +700,7 @@ internal class DefaultCryptoService @Inject constructor( keyShareLock.withLock { coroutineScope { - olmMachine!!.shareRoomKey(roomId, roomMembers).map { + this@DefaultCryptoService.olmMachine!!.shareRoomKey(roomId, roomMembers).map { when (it) { is Request.ToDevice -> { async { @@ -745,14 +734,14 @@ internal class DefaultCryptoService @Inject constructor( val response = uploadKeysTask.execute(request) val adapter = MoshiProvider .providesMoshi() - .adapter(KeysUploadResponse::class.java) + .adapter(KeysUploadResponse::class.java) - val json_response = adapter.toJson(response)!! + val jsonResponse = adapter.toJson(response)!! - olmMachine!!.markRequestAsSent( + this.olmMachine!!.markRequestAsSent( outgoingRequest.requestId, RequestType.KEYS_UPLOAD, - json_response + jsonResponse ) } @@ -761,9 +750,9 @@ internal class DefaultCryptoService @Inject constructor( try { val response = downloadKeysForUsersTask.execute(params) - val adapter = MoshiProvider.providesMoshi().adapter(KeysQueryResponse::class.java) - val json_response = adapter.toJson(response)!! - olmMachine!!.markRequestAsSent(outgoingRequest.requestId, RequestType.KEYS_QUERY, json_response) + val adapter = MoshiProvider.providesMoshi().adapter(KeysQueryResponse::class.java) + val jsonResponse = adapter.toJson(response)!! + this.olmMachine!!.markRequestAsSent(outgoingRequest.requestId, RequestType.KEYS_QUERY, jsonResponse) } catch (throwable: Throwable) { Timber.e(throwable, "## CRYPTO | doKeyDownloadForUsers(): error") } @@ -790,14 +779,14 @@ internal class DefaultCryptoService @Inject constructor( val response = oneTimeKeysForUsersDeviceTask.execute(claimParams) val adapter = MoshiProvider .providesMoshi() - .adapter(KeysClaimResponse::class.java) - val json_response = adapter.toJson(response)!! + .adapter(KeysClaimResponse::class.java) + val jsonResponse = adapter.toJson(response)!! - olmMachine!!.markRequestAsSent(request.requestId, RequestType.KEYS_CLAIM, json_response) + olmMachine!!.markRequestAsSent(request.requestId, RequestType.KEYS_CLAIM, jsonResponse) } private suspend fun sendOutgoingRequests() { - outgointRequestsLock.withLock { + outgoingRequestsLock.withLock { coroutineScope { olmMachine!!.outgoingRequests().map { when (it) { @@ -995,9 +984,9 @@ internal class DefaultCryptoService @Inject constructor( if (forceDownload) { // TODO replicate the logic from the device list manager // where we would download the fresh info from the server. - olmMachine?.getUserDevicesMap(userIds) ?: MXUsersDevicesMap() + this@DefaultCryptoService.olmMachine?.getUserDevicesMap(userIds) ?: MXUsersDevicesMap() } else { - olmMachine?.getUserDevicesMap(userIds) ?: MXUsersDevicesMap() + this@DefaultCryptoService.olmMachine?.getUserDevicesMap(userIds) ?: MXUsersDevicesMap() } }.foldToCallback(callback) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OlmMachine.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OlmMachine.kt index ecb632be8b..e234c3cd0a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OlmMachine.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OlmMachine.kt @@ -51,7 +51,7 @@ import uniffi.olm.Request import uniffi.olm.RequestType import uniffi.olm.setLogger -class CryptoLogger() : Logger { +class CryptoLogger : Logger { override fun log(logLine: String) { Timber.d(logLine) } @@ -68,11 +68,9 @@ private class CryptoProgressListener(listener: ProgressListener?) : RustProgress } internal class LiveDevice( - userIds: List, - observer: DeviceUpdateObserver + internal var userIds: List, + private var observer: DeviceUpdateObserver ) : MutableLiveData>() { - internal var userIds: List = userIds - private var observer: DeviceUpdateObserver = observer override fun onActive() { observer.addDeviceUpdateListener(this) @@ -105,18 +103,18 @@ private fun toCryptoDeviceInfo(device: Device): CryptoDeviceInfo { mapOf(), UnsignedDeviceInfo(device.displayName), // TODO pass trust levels here - DeviceTrustLevel(false, false), + DeviceTrustLevel(crossSigningVerified = false, locallyVerified = false), device.isBlocked, // TODO null ) } -internal class DeviceUpdateObserver() { +internal class DeviceUpdateObserver { internal val listeners = ConcurrentHashMap>() fun addDeviceUpdateListener(device: LiveDevice) { - listeners.set(device, device.userIds) + listeners[device] = device.userIds } fun removeDeviceUpdateListener(device: LiveDevice) { @@ -164,7 +162,7 @@ internal class OlmMachine(user_id: String, device_id: String, path: File, device keys, mapOf(), UnsignedDeviceInfo(), - DeviceTrustLevel(false, true), + DeviceTrustLevel(crossSigningVerified = false, locallyVerified = true), false, null ) @@ -226,14 +224,14 @@ internal class OlmMachine(user_id: String, device_id: String, path: File, device deviceChanges: DeviceListResponse?, keyCounts: DeviceOneTimeKeysCountSyncResponse? ): ToDeviceSyncResponse = withContext(Dispatchers.IO) { - var counts: MutableMap = mutableMapOf() + val counts: MutableMap = mutableMapOf() if (keyCounts?.signedCurve25519 != null) { - counts.put("signed_curve25519", keyCounts.signedCurve25519) + counts["signed_curve25519"] = keyCounts.signedCurve25519 } val devices = DeviceLists(deviceChanges?.changed ?: listOf(), deviceChanges?.left ?: listOf()) - val adapter = MoshiProvider.providesMoshi().adapter(ToDeviceSyncResponse::class.java) + val adapter = MoshiProvider.providesMoshi().adapter(ToDeviceSyncResponse::class.java) val events = adapter.toJson(toDevice ?: ToDeviceSyncResponse())!! adapter.fromJson(inner.receiveSyncChanges(events, devices, counts))!! @@ -351,7 +349,7 @@ internal class OlmMachine(user_id: String, device_id: String, path: File, device */ @Throws(MXCryptoError::class) suspend fun decryptRoomEvent(event: Event): MXEventDecryptionResult = withContext(Dispatchers.IO) { - val adapter = MoshiProvider.providesMoshi().adapter(Event::class.java) + val adapter = MoshiProvider.providesMoshi().adapter(Event::class.java) val serializedEvent = adapter.toJson(event) try { @@ -385,7 +383,7 @@ internal class OlmMachine(user_id: String, device_id: String, path: File, device */ @Throws(DecryptionErrorException::class) suspend fun requestRoomKey(event: Event): KeyRequestPair = withContext(Dispatchers.IO) { - val adapter = MoshiProvider.providesMoshi().adapter(Event::class.java) + val adapter = MoshiProvider.providesMoshi().adapter(Event::class.java) val serializedEvent = adapter.toJson(event) inner.requestRoomKey(serializedEvent, event.roomId!!) @@ -421,9 +419,9 @@ internal class OlmMachine(user_id: String, device_id: String, path: File, device suspend fun importKeys(keys: ByteArray, passphrase: String, listener: ProgressListener?): ImportRoomKeysResult = withContext(Dispatchers.IO) { val decodedKeys = String(keys, Charset.defaultCharset()) - var rustListener = CryptoProgressListener(listener) + val rustListener = CryptoProgressListener(listener) - var result = inner.importKeys(decodedKeys, passphrase, rustListener) + val result = inner.importKeys(decodedKeys, passphrase, rustListener) ImportRoomKeysResult(result.total, result.imported) } @@ -459,7 +457,7 @@ internal class OlmMachine(user_id: String, device_id: String, path: File, device @Throws(CryptoStoreErrorException::class) suspend fun getUserDevices(userId: String): List { val ownDevice = ownDevice() - var devices = inner.getUserDevices(userId).map { toCryptoDeviceInfo(it) }.toMutableList() + val devices = inner.getUserDevices(userId).map { toCryptoDeviceInfo(it) }.toMutableList() // EA doesn't differentiate much between our own and other devices of // while the rust-sdk does, append our own device here. @@ -485,7 +483,7 @@ internal class OlmMachine(user_id: String, device_id: String, path: File, device /** * Get all the devices of multiple users. * - * @param userId The ids of the device owners. + * @param userIds The ids of the device owners. * * @return The list of Devices or an empty list if there aren't any. */ @@ -516,14 +514,14 @@ internal class OlmMachine(user_id: String, device_id: String, path: File, device * The live version will update the list of devices if some of the data * changes, or if new devices arrive for a certain user. * - * @param userId The ids of the device owners. + * @param userIds The ids of the device owners. * * @return The list of Devices or an empty list if there aren't any. */ suspend fun getLiveDevices(userIds: List): LiveData> { val plainDevices = getUserDevices(userIds) val devices = LiveDevice(userIds, deviceUpdateObserver) - devices.setValue(plainDevices) + devices.value = plainDevices return devices } @@ -533,8 +531,6 @@ internal class OlmMachine(user_id: String, device_id: String, path: File, device */ @Throws(CryptoStoreErrorException::class) fun discardRoomKey(roomId: String) { - runBlocking { - inner.discardRoomKey(roomId) - } + runBlocking { inner.discardRoomKey(roomId) } } }