crypto: Fix a bunch of linter warnings

This commit is contained in:
Damir Jelić 2021-04-27 16:33:13 +02:00
parent 324cdc4db1
commit fe4abbbeef
2 changed files with 52 additions and 67 deletions

View file

@ -160,7 +160,7 @@ internal class DefaultCryptoService @Inject constructor(
// Locks for some of our operations // Locks for some of our operations
private val keyClaimLock: Mutex = Mutex() private val keyClaimLock: Mutex = Mutex()
private val outgointRequestsLock: Mutex = Mutex() private val outgoingRequestsLock: Mutex = Mutex()
private val roomKeyShareLocks: ConcurrentHashMap<String, Mutex> = ConcurrentHashMap() private val roomKeyShareLocks: ConcurrentHashMap<String, Mutex> = ConcurrentHashMap()
// TODO does this need to be concurrent? // TODO does this need to be concurrent?
@ -182,7 +182,7 @@ internal class DefaultCryptoService @Inject constructor(
} }
} }
val gossipingBuffer = mutableListOf<Event>() private val gossipingBuffer = mutableListOf<Event>()
override fun setDeviceName(deviceId: String, deviceName: String, callback: MatrixCallback<Unit>) { override fun setDeviceName(deviceId: String, deviceName: String, callback: MatrixCallback<Unit>) {
setDeviceNameTask setDeviceNameTask
@ -217,9 +217,7 @@ internal class DefaultCryptoService @Inject constructor(
return if (longFormat) "Rust SDK 0.3" else "0.3" return if (longFormat) "Rust SDK 0.3" else "0.3"
} }
override fun getMyDevice(): CryptoDeviceInfo { override fun getMyDevice(): CryptoDeviceInfo = this.olmMachine!!.ownDevice()
return olmMachine!!.ownDevice()
}
override fun fetchDevicesList(callback: MatrixCallback<DevicesListResponse>) { override fun fetchDevicesList(callback: MatrixCallback<DevicesListResponse>) {
getDevicesTask getDevicesTask
@ -280,15 +278,6 @@ internal class DefaultCryptoService @Inject constructor(
return isStarted.get() 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. * Start the crypto module.
* Device keys will be uploaded, then one time keys if there are not enough on the homeserver * 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 { try {
setRustLogger() setRustLogger()
olmMachine = OlmMachine(userId, deviceId!!, dataDir, deviceObserver) this.olmMachine = OlmMachine(userId, deviceId!!, dataDir, deviceObserver)
Timber.v( Timber.v(
"## CRYPTO | Successfully started up an Olm machine for " + "## CRYPTO | Successfully started up an Olm machine for " +
"${userId}, ${deviceId}, identity keys: ${olmMachine?.identityKeys()}") "${userId}, ${deviceId}, identity keys: ${this.olmMachine?.identityKeys()}")
} catch (throwable: Throwable) { } catch (throwable: Throwable) {
Timber.v("Failed create an Olm machine: $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? { override fun getDeviceInfo(userId: String, deviceId: String?): CryptoDeviceInfo? {
return if (userId.isNotEmpty() && !deviceId.isNullOrEmpty()) { return if (userId.isNotEmpty() && !deviceId.isNullOrEmpty()) {
runBlocking { runBlocking {
olmMachine?.getDevice(userId, deviceId) this@DefaultCryptoService.olmMachine?.getDevice(userId, deviceId)
} }
} else { } else {
null null
@ -410,7 +399,7 @@ internal class DefaultCryptoService @Inject constructor(
override fun getCryptoDeviceInfo(userId: String): List<CryptoDeviceInfo> { override fun getCryptoDeviceInfo(userId: String): List<CryptoDeviceInfo> {
return runBlocking { 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<String>): LiveData<List<CryptoDeviceInfo>> { override fun getLiveCryptoDeviceInfo(userIds: List<String>): LiveData<List<CryptoDeviceInfo>> {
return runBlocking { 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) @Throws(MXCryptoError::class)
override fun decryptEvent(event: Event, timeline: String): MXEventDecryptionResult { override fun decryptEvent(event: Event, timeline: String): MXEventDecryptionResult {
val decrypted = runBlocking {
return runBlocking {
olmMachine!!.decryptRoomEvent(event) olmMachine!!.decryptRoomEvent(event)
} }
return decrypted
} }
/** /**
@ -670,22 +658,22 @@ internal class DefaultCryptoService @Inject constructor(
deviceChanges: DeviceListResponse?, deviceChanges: DeviceListResponse?,
keyCounts: DeviceOneTimeKeysCountSyncResponse?) { keyCounts: DeviceOneTimeKeysCountSyncResponse?) {
// Decrypt and handle our to-device events // 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. // Notify the our listeners about room keys so decryption is retried.
if (toDeviceEvents.events != null) { if (toDeviceEvents.events != null) {
for (event in toDeviceEvents.events) { toDeviceEvents.events.forEach { event ->
if (event.type == "m.room_key") { if (event.type == "m.room_key") {
val content = event.getClearContent().toModel<RoomKeyContent>() ?: continue val content = event.getClearContent().toModel<RoomKeyContent>() ?: return@forEach
val roomId = content.sessionId ?: continue val roomId = content.sessionId ?: return@forEach
val sessionId = content.sessionId val sessionId = content.sessionId
notifyRoomKeyReceival(roomId, sessionId) notifyRoomKeyReceival(roomId, sessionId)
} else if (event.type == "m.forwarded_room_key") { } else if (event.type == "m.forwarded_room_key") {
val content = event.getClearContent().toModel<ForwardedRoomKeyContent>() ?: continue val content = event.getClearContent().toModel<ForwardedRoomKeyContent>() ?: return@forEach
val roomId = content.sessionId ?: continue val roomId = content.sessionId ?: return@forEach
val sessionId = content.sessionId val sessionId = content.sessionId
notifyRoomKeyReceival(roomId, sessionId) notifyRoomKeyReceival(roomId, sessionId)
@ -696,13 +684,14 @@ internal class DefaultCryptoService @Inject constructor(
private suspend fun preshareRoomKey(roomId: String, roomMembers: List<String>) { private suspend fun preshareRoomKey(roomId: String, roomMembers: List<String>) {
keyClaimLock.withLock { 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) { if (request != null) {
// This request can only be a keys claim request.
when (request) { when (request) {
is Request.KeysClaim -> { is Request.KeysClaim -> {
claimKeys(request) claimKeys(request)
} }
else -> {}
} }
} }
} }
@ -711,7 +700,7 @@ internal class DefaultCryptoService @Inject constructor(
keyShareLock.withLock { keyShareLock.withLock {
coroutineScope { coroutineScope {
olmMachine!!.shareRoomKey(roomId, roomMembers).map { this@DefaultCryptoService.olmMachine!!.shareRoomKey(roomId, roomMembers).map {
when (it) { when (it) {
is Request.ToDevice -> { is Request.ToDevice -> {
async { async {
@ -745,14 +734,14 @@ internal class DefaultCryptoService @Inject constructor(
val response = uploadKeysTask.execute(request) val response = uploadKeysTask.execute(request)
val adapter = MoshiProvider val adapter = MoshiProvider
.providesMoshi() .providesMoshi()
.adapter<KeysUploadResponse>(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, outgoingRequest.requestId,
RequestType.KEYS_UPLOAD, RequestType.KEYS_UPLOAD,
json_response jsonResponse
) )
} }
@ -761,9 +750,9 @@ internal class DefaultCryptoService @Inject constructor(
try { try {
val response = downloadKeysForUsersTask.execute(params) val response = downloadKeysForUsersTask.execute(params)
val adapter = MoshiProvider.providesMoshi().adapter<KeysQueryResponse>(KeysQueryResponse::class.java) val adapter = MoshiProvider.providesMoshi().adapter(KeysQueryResponse::class.java)
val json_response = adapter.toJson(response)!! val jsonResponse = adapter.toJson(response)!!
olmMachine!!.markRequestAsSent(outgoingRequest.requestId, RequestType.KEYS_QUERY, json_response) this.olmMachine!!.markRequestAsSent(outgoingRequest.requestId, RequestType.KEYS_QUERY, jsonResponse)
} catch (throwable: Throwable) { } catch (throwable: Throwable) {
Timber.e(throwable, "## CRYPTO | doKeyDownloadForUsers(): error") Timber.e(throwable, "## CRYPTO | doKeyDownloadForUsers(): error")
} }
@ -790,14 +779,14 @@ internal class DefaultCryptoService @Inject constructor(
val response = oneTimeKeysForUsersDeviceTask.execute(claimParams) val response = oneTimeKeysForUsersDeviceTask.execute(claimParams)
val adapter = MoshiProvider val adapter = MoshiProvider
.providesMoshi() .providesMoshi()
.adapter<KeysClaimResponse>(KeysClaimResponse::class.java) .adapter(KeysClaimResponse::class.java)
val json_response = adapter.toJson(response)!! 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() { private suspend fun sendOutgoingRequests() {
outgointRequestsLock.withLock { outgoingRequestsLock.withLock {
coroutineScope { coroutineScope {
olmMachine!!.outgoingRequests().map { olmMachine!!.outgoingRequests().map {
when (it) { when (it) {
@ -995,9 +984,9 @@ internal class DefaultCryptoService @Inject constructor(
if (forceDownload) { if (forceDownload) {
// TODO replicate the logic from the device list manager // TODO replicate the logic from the device list manager
// where we would download the fresh info from the server. // where we would download the fresh info from the server.
olmMachine?.getUserDevicesMap(userIds) ?: MXUsersDevicesMap() this@DefaultCryptoService.olmMachine?.getUserDevicesMap(userIds) ?: MXUsersDevicesMap()
} else { } else {
olmMachine?.getUserDevicesMap(userIds) ?: MXUsersDevicesMap() this@DefaultCryptoService.olmMachine?.getUserDevicesMap(userIds) ?: MXUsersDevicesMap()
} }
}.foldToCallback(callback) }.foldToCallback(callback)
} }

View file

@ -51,7 +51,7 @@ import uniffi.olm.Request
import uniffi.olm.RequestType import uniffi.olm.RequestType
import uniffi.olm.setLogger import uniffi.olm.setLogger
class CryptoLogger() : Logger { class CryptoLogger : Logger {
override fun log(logLine: String) { override fun log(logLine: String) {
Timber.d(logLine) Timber.d(logLine)
} }
@ -68,11 +68,9 @@ private class CryptoProgressListener(listener: ProgressListener?) : RustProgress
} }
internal class LiveDevice( internal class LiveDevice(
userIds: List<String>, internal var userIds: List<String>,
observer: DeviceUpdateObserver private var observer: DeviceUpdateObserver
) : MutableLiveData<List<CryptoDeviceInfo>>() { ) : MutableLiveData<List<CryptoDeviceInfo>>() {
internal var userIds: List<String> = userIds
private var observer: DeviceUpdateObserver = observer
override fun onActive() { override fun onActive() {
observer.addDeviceUpdateListener(this) observer.addDeviceUpdateListener(this)
@ -105,18 +103,18 @@ private fun toCryptoDeviceInfo(device: Device): CryptoDeviceInfo {
mapOf(), mapOf(),
UnsignedDeviceInfo(device.displayName), UnsignedDeviceInfo(device.displayName),
// TODO pass trust levels here // TODO pass trust levels here
DeviceTrustLevel(false, false), DeviceTrustLevel(crossSigningVerified = false, locallyVerified = false),
device.isBlocked, device.isBlocked,
// TODO // TODO
null null
) )
} }
internal class DeviceUpdateObserver() { internal class DeviceUpdateObserver {
internal val listeners = ConcurrentHashMap<LiveDevice, List<String>>() internal val listeners = ConcurrentHashMap<LiveDevice, List<String>>()
fun addDeviceUpdateListener(device: LiveDevice) { fun addDeviceUpdateListener(device: LiveDevice) {
listeners.set(device, device.userIds) listeners[device] = device.userIds
} }
fun removeDeviceUpdateListener(device: LiveDevice) { fun removeDeviceUpdateListener(device: LiveDevice) {
@ -164,7 +162,7 @@ internal class OlmMachine(user_id: String, device_id: String, path: File, device
keys, keys,
mapOf(), mapOf(),
UnsignedDeviceInfo(), UnsignedDeviceInfo(),
DeviceTrustLevel(false, true), DeviceTrustLevel(crossSigningVerified = false, locallyVerified = true),
false, false,
null null
) )
@ -226,14 +224,14 @@ internal class OlmMachine(user_id: String, device_id: String, path: File, device
deviceChanges: DeviceListResponse?, deviceChanges: DeviceListResponse?,
keyCounts: DeviceOneTimeKeysCountSyncResponse? keyCounts: DeviceOneTimeKeysCountSyncResponse?
): ToDeviceSyncResponse = withContext(Dispatchers.IO) { ): ToDeviceSyncResponse = withContext(Dispatchers.IO) {
var counts: MutableMap<String, Int> = mutableMapOf() val counts: MutableMap<String, Int> = mutableMapOf()
if (keyCounts?.signedCurve25519 != null) { 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 devices = DeviceLists(deviceChanges?.changed ?: listOf(), deviceChanges?.left ?: listOf())
val adapter = MoshiProvider.providesMoshi().adapter<ToDeviceSyncResponse>(ToDeviceSyncResponse::class.java) val adapter = MoshiProvider.providesMoshi().adapter(ToDeviceSyncResponse::class.java)
val events = adapter.toJson(toDevice ?: ToDeviceSyncResponse())!! val events = adapter.toJson(toDevice ?: ToDeviceSyncResponse())!!
adapter.fromJson(inner.receiveSyncChanges(events, devices, counts))!! 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) @Throws(MXCryptoError::class)
suspend fun decryptRoomEvent(event: Event): MXEventDecryptionResult = withContext(Dispatchers.IO) { suspend fun decryptRoomEvent(event: Event): MXEventDecryptionResult = withContext(Dispatchers.IO) {
val adapter = MoshiProvider.providesMoshi().adapter<Event>(Event::class.java) val adapter = MoshiProvider.providesMoshi().adapter(Event::class.java)
val serializedEvent = adapter.toJson(event) val serializedEvent = adapter.toJson(event)
try { try {
@ -385,7 +383,7 @@ internal class OlmMachine(user_id: String, device_id: String, path: File, device
*/ */
@Throws(DecryptionErrorException::class) @Throws(DecryptionErrorException::class)
suspend fun requestRoomKey(event: Event): KeyRequestPair = withContext(Dispatchers.IO) { suspend fun requestRoomKey(event: Event): KeyRequestPair = withContext(Dispatchers.IO) {
val adapter = MoshiProvider.providesMoshi().adapter<Event>(Event::class.java) val adapter = MoshiProvider.providesMoshi().adapter(Event::class.java)
val serializedEvent = adapter.toJson(event) val serializedEvent = adapter.toJson(event)
inner.requestRoomKey(serializedEvent, event.roomId!!) 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) { suspend fun importKeys(keys: ByteArray, passphrase: String, listener: ProgressListener?): ImportRoomKeysResult = withContext(Dispatchers.IO) {
val decodedKeys = String(keys, Charset.defaultCharset()) 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) ImportRoomKeysResult(result.total, result.imported)
} }
@ -459,7 +457,7 @@ internal class OlmMachine(user_id: String, device_id: String, path: File, device
@Throws(CryptoStoreErrorException::class) @Throws(CryptoStoreErrorException::class)
suspend fun getUserDevices(userId: String): List<CryptoDeviceInfo> { suspend fun getUserDevices(userId: String): List<CryptoDeviceInfo> {
val ownDevice = ownDevice() 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 // EA doesn't differentiate much between our own and other devices of
// while the rust-sdk does, append our own device here. // 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. * 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. * @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 * The live version will update the list of devices if some of the data
* changes, or if new devices arrive for a certain user. * 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. * @return The list of Devices or an empty list if there aren't any.
*/ */
suspend fun getLiveDevices(userIds: List<String>): LiveData<List<CryptoDeviceInfo>> { suspend fun getLiveDevices(userIds: List<String>): LiveData<List<CryptoDeviceInfo>> {
val plainDevices = getUserDevices(userIds) val plainDevices = getUserDevices(userIds)
val devices = LiveDevice(userIds, deviceUpdateObserver) val devices = LiveDevice(userIds, deviceUpdateObserver)
devices.setValue(plainDevices) devices.value = plainDevices
return devices return devices
} }
@ -533,8 +531,6 @@ internal class OlmMachine(user_id: String, device_id: String, path: File, device
*/ */
@Throws(CryptoStoreErrorException::class) @Throws(CryptoStoreErrorException::class)
fun discardRoomKey(roomId: String) { fun discardRoomKey(roomId: String) {
runBlocking { runBlocking { inner.discardRoomKey(roomId) }
inner.discardRoomKey(roomId)
}
} }
} }