Refactor error handling and report E2EE errors

This commit is contained in:
Hugh Nimmo-Smith 2022-10-17 16:02:25 +01:00
parent d616251f26
commit e01ee619d3
11 changed files with 171 additions and 146 deletions

View File

@ -3383,6 +3383,12 @@
<string name="qr_code_login_header_failed_timeout_description">The linking wasnt completed in the required time.</string> <string name="qr_code_login_header_failed_timeout_description">The linking wasnt completed in the required time.</string>
<string name="qr_code_login_header_failed_denied_description">The request was denied on the other device.</string> <string name="qr_code_login_header_failed_denied_description">The request was denied on the other device.</string>
<string name="qr_code_login_header_failed_other_description">The request failed.</string> <string name="qr_code_login_header_failed_other_description">The request failed.</string>
<string name="qr_code_login_header_failed_e2ee_security_issue_description">A security issue was encountered setting up secure messaging. One of the following may be compromised: Your homeserver; Your intent connection(s); Your device(s);</string>
<string name="qr_code_login_header_failed_other_device_already_signed_in_description">The other device is already signed in.</string>
<string name="qr_code_login_header_failed_other_device_not_signed_in_description">The other device must be signed in.</string>
<string name="qr_code_login_header_failed_invalid_qr_code_description">The QR code scanned is invalid.</string>
<string name="qr_code_login_header_failed_user_cancelled_description">The sign in was cancelled on the other device.</string>
<string name="qr_code_login_header_failed_homeserver_is_not_supported_description">The homeserver doesn\'t support sign in with QR code.</string>
<string name="qr_code_login_new_device_instruction_1">Open ${app_name} on your other device</string> <string name="qr_code_login_new_device_instruction_1">Open ${app_name} on your other device</string>
<string name="qr_code_login_new_device_instruction_2">Go to Settings -> Security &amp; Privacy -> Show All Sessions</string> <string name="qr_code_login_new_device_instruction_2">Go to Settings -> Security &amp; Privacy -> Show All Sessions</string>
<string name="qr_code_login_new_device_instruction_3">Select \'Show QR code in this device\'</string> <string name="qr_code_login_new_device_instruction_3">Select \'Show QR code in this device\'</string>

View File

@ -26,6 +26,7 @@ import org.matrix.android.sdk.api.rendezvous.model.Outcome
import org.matrix.android.sdk.api.rendezvous.model.Payload import org.matrix.android.sdk.api.rendezvous.model.Payload
import org.matrix.android.sdk.api.rendezvous.model.PayloadType import org.matrix.android.sdk.api.rendezvous.model.PayloadType
import org.matrix.android.sdk.api.rendezvous.model.Protocol import org.matrix.android.sdk.api.rendezvous.model.Protocol
import org.matrix.android.sdk.api.rendezvous.model.RendezvousError
import org.matrix.android.sdk.api.rendezvous.model.RendezvousIntent import org.matrix.android.sdk.api.rendezvous.model.RendezvousIntent
import org.matrix.android.sdk.api.rendezvous.transports.SimpleHttpRendezvousTransport import org.matrix.android.sdk.api.rendezvous.transports.SimpleHttpRendezvousTransport
import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.Session
@ -47,10 +48,16 @@ class Rendezvous(
companion object { companion object {
private val TAG = LoggerTag(Rendezvous::class.java.simpleName, LoggerTag.RENDEZVOUS).value private val TAG = LoggerTag(Rendezvous::class.java.simpleName, LoggerTag.RENDEZVOUS).value
fun buildChannelFromCode(code: String, onCancelled: (reason: RendezvousFailureReason) -> Unit): Rendezvous { @Throws(RendezvousError::class)
val parsed = MatrixJsonParser.getMoshi().adapter(ECDHRendezvousCode::class.java).fromJson(code) ?: throw RuntimeException("Invalid code") fun buildChannelFromCode(code: String): Rendezvous {
val parsed = try {
// we rely on moshi validating the code and throwing exception if invalid JSON or doesn't
MatrixJsonParser.getMoshi().adapter(ECDHRendezvousCode::class.java).fromJson(code)
} catch (a: Throwable) {
throw RendezvousError("Invalid code", RendezvousFailureReason.InvalidCode)
} ?: throw RendezvousError("Invalid code", RendezvousFailureReason.InvalidCode)
val transport = SimpleHttpRendezvousTransport(onCancelled, parsed.rendezvous.transport.uri) val transport = SimpleHttpRendezvousTransport(parsed.rendezvous.transport.uri)
return Rendezvous( return Rendezvous(
ECDHRendezvousChannel(transport, parsed.rendezvous.key), ECDHRendezvousChannel(transport, parsed.rendezvous.key),
@ -64,32 +71,30 @@ class Rendezvous(
// not yet implemented: RendezvousIntent.RECIPROCATE_LOGIN_ON_EXISTING_DEVICE // not yet implemented: RendezvousIntent.RECIPROCATE_LOGIN_ON_EXISTING_DEVICE
val ourIntent: RendezvousIntent = RendezvousIntent.LOGIN_ON_NEW_DEVICE val ourIntent: RendezvousIntent = RendezvousIntent.LOGIN_ON_NEW_DEVICE
private suspend fun areIntentsIncompatible(): Boolean { @Throws(RendezvousError::class)
private suspend fun checkCompatibility() {
val incompatible = theirIntent == ourIntent val incompatible = theirIntent == ourIntent
Timber.tag(TAG).d("ourIntent: $ourIntent, theirIntent: $theirIntent, incompatible: $incompatible") Timber.tag(TAG).d("ourIntent: $ourIntent, theirIntent: $theirIntent, incompatible: $incompatible")
if (incompatible) { if (incompatible) {
// inform the other side
send(Payload(PayloadType.FINISH, intent = ourIntent)) send(Payload(PayloadType.FINISH, intent = ourIntent))
val reason = if (ourIntent == RendezvousIntent.LOGIN_ON_NEW_DEVICE) { if (ourIntent == RendezvousIntent.LOGIN_ON_NEW_DEVICE) {
RendezvousFailureReason.OtherDeviceNotSignedIn throw RendezvousError("The other device isn't signed in", RendezvousFailureReason.OtherDeviceNotSignedIn)
} else { } else {
RendezvousFailureReason.OtherDeviceAlreadySignedIn throw RendezvousError("The other device is already signed in", RendezvousFailureReason.OtherDeviceAlreadySignedIn)
} }
channel.cancel(reason)
} }
return incompatible
} }
@Throws(RendezvousError::class)
suspend fun startAfterScanningCode(): String? { suspend fun startAfterScanningCode(): String? {
val checksum = channel.connect() val checksum = channel.connect()
Timber.tag(TAG).i("Connected to secure channel with checksum: $checksum") Timber.tag(TAG).i("Connected to secure channel with checksum: $checksum")
if (areIntentsIncompatible()) { checkCompatibility()
return null
}
// get protocols // get protocols
Timber.tag(TAG).i("Waiting for protocols") Timber.tag(TAG).i("Waiting for protocols")
@ -97,9 +102,7 @@ class Rendezvous(
if (protocolsResponse?.protocols == null || !protocolsResponse.protocols.contains(Protocol.LOGIN_TOKEN)) { if (protocolsResponse?.protocols == null || !protocolsResponse.protocols.contains(Protocol.LOGIN_TOKEN)) {
send(Payload(PayloadType.FINISH, outcome = Outcome.UNSUPPORTED)) send(Payload(PayloadType.FINISH, outcome = Outcome.UNSUPPORTED))
Timber.tag(TAG).i("No supported protocol") throw RendezvousError("Unsupported protocols", RendezvousFailureReason.UnsupportedHomeserver)
cancel(RendezvousFailureReason.Unknown)
return null
} }
send(Payload(PayloadType.PROGRESS, protocol = Protocol.LOGIN_TOKEN)) send(Payload(PayloadType.PROGRESS, protocol = Protocol.LOGIN_TOKEN))
@ -107,6 +110,7 @@ class Rendezvous(
return checksum return checksum
} }
@Throws(RendezvousError::class)
suspend fun waitForLoginOnNewDevice(authenticationService: AuthenticationService): Session? { suspend fun waitForLoginOnNewDevice(authenticationService: AuthenticationService): Session? {
Timber.tag(TAG).i("Waiting for login_token") Timber.tag(TAG).i("Waiting for login_token")
@ -115,24 +119,19 @@ class Rendezvous(
if (loginToken?.type == PayloadType.FINISH) { if (loginToken?.type == PayloadType.FINISH) {
when (loginToken.outcome) { when (loginToken.outcome) {
Outcome.DECLINED -> { Outcome.DECLINED -> {
Timber.tag(TAG).i("Login declined by other device") throw RendezvousError("Login declined by other device", RendezvousFailureReason.UserDeclined)
channel.cancel(RendezvousFailureReason.UserDeclined)
return null
} }
Outcome.UNSUPPORTED -> { Outcome.UNSUPPORTED -> {
Timber.tag(TAG).i("Not supported") throw RendezvousError("Homeserver lacks support", RendezvousFailureReason.UnsupportedHomeserver)
channel.cancel(RendezvousFailureReason.HomeserverLacksSupport)
return null
} }
else -> { else -> {
channel.cancel(RendezvousFailureReason.Unknown) throw RendezvousError("Unknown error", RendezvousFailureReason.Unknown)
return null
} }
} }
} }
val homeserver = loginToken?.homeserver ?: throw RuntimeException("No homeserver returned") val homeserver = loginToken?.homeserver ?: throw RendezvousError("No homeserver returned", RendezvousFailureReason.ProtocolError)
val token = loginToken.loginToken ?: throw RuntimeException("No login token returned") val token = loginToken.loginToken ?: throw RendezvousError("No login token returned", RendezvousFailureReason.ProtocolError)
Timber.tag(TAG).i("Got login_token now attempting to sign in with $homeserver") Timber.tag(TAG).i("Got login_token now attempting to sign in with $homeserver")
@ -140,6 +139,7 @@ class Rendezvous(
return authenticationService.loginUsingQrLoginToken(hsConfig, token) return authenticationService.loginUsingQrLoginToken(hsConfig, token)
} }
@Throws(RendezvousError::class)
suspend fun completeVerificationOnNewDevice(session: Session) { suspend fun completeVerificationOnNewDevice(session: Session) {
val userId = session.myUserId val userId = session.myUserId
val crypto = session.cryptoService() val crypto = session.cryptoService()
@ -148,59 +148,77 @@ class Rendezvous(
send(Payload(PayloadType.PROGRESS, outcome = Outcome.SUCCESS, deviceId = deviceId, deviceKey = deviceKey)) send(Payload(PayloadType.PROGRESS, outcome = Outcome.SUCCESS, deviceId = deviceId, deviceKey = deviceKey))
// await confirmation of verification // await confirmation of verification
val verificationResponse = receive() val verificationResponse = receive()
val verifyingDeviceId = verificationResponse?.verifyingDeviceId ?: throw RuntimeException("No verifying device id returned") if (verificationResponse?.outcome == Outcome.VERIFIED) {
val verifyingDeviceFromServer = crypto.getCryptoDeviceInfo(userId, verifyingDeviceId) val verifyingDeviceId = verificationResponse.verifyingDeviceId
if (verifyingDeviceFromServer?.fingerprint() != verificationResponse.verifyingDeviceKey) { ?: throw RendezvousError("No verifying device id returned", RendezvousFailureReason.ProtocolError)
Timber.tag(TAG).w( val verifyingDeviceFromServer = crypto.getCryptoDeviceInfo(userId, verifyingDeviceId)
"Verifying device $verifyingDeviceId key doesn't match: ${ if (verifyingDeviceFromServer?.fingerprint() != verificationResponse.verifyingDeviceKey) {
verifyingDeviceFromServer?.fingerprint()} vs ${verificationResponse.verifyingDeviceKey})" Timber.tag(TAG).w(
) "Verifying device $verifyingDeviceId key doesn't match: ${
throw RuntimeException("Key from verifying device doesn't match") verifyingDeviceFromServer?.fingerprint()
} } vs ${verificationResponse.verifyingDeviceKey})"
)
// inform the other side
send(Payload(PayloadType.FINISH, outcome = Outcome.E2EE_SECURITY_ERROR))
throw RendezvousError("Key from verifying device doesn't match", RendezvousFailureReason.E2EESecurityIssue)
}
// set other device as verified verificationResponse.masterKey?.let { masterKeyFromVerifyingDevice ->
Timber.tag(TAG).i("Setting device $verifyingDeviceId as verified") // check master key againt what the homeserver told us
crypto.setDeviceVerification(DeviceTrustLevel(locallyVerified = true, crossSigningVerified = false), userId, verifyingDeviceId) crypto.crossSigningService().getMyCrossSigningKeys()?.masterKey()?.let { localMasterKey ->
if (localMasterKey.unpaddedBase64PublicKey != masterKeyFromVerifyingDevice) {
Timber.tag(TAG).w("Master key from verifying device doesn't match: $masterKeyFromVerifyingDevice vs $localMasterKey")
// inform the other side
send(Payload(PayloadType.FINISH, outcome = Outcome.E2EE_SECURITY_ERROR))
throw RendezvousError("Master key from verifying device doesn't match", RendezvousFailureReason.E2EESecurityIssue)
}
// set other device as verified
Timber.tag(TAG).i("Setting device $verifyingDeviceId as verified")
crypto.setDeviceVerification(DeviceTrustLevel(locallyVerified = true, crossSigningVerified = false), userId, verifyingDeviceId)
verificationResponse.masterKey ?.let { masterKeyFromVerifyingDevice ->
// set master key as trusted
crypto.crossSigningService().getMyCrossSigningKeys()?.masterKey()?.let { localMasterKey ->
if (localMasterKey.unpaddedBase64PublicKey == masterKeyFromVerifyingDevice) {
Timber.tag(TAG).i("Setting master key as trusted") Timber.tag(TAG).i("Setting master key as trusted")
crypto.crossSigningService().markMyMasterKeyAsTrusted() crypto.crossSigningService().markMyMasterKeyAsTrusted()
} else { } ?: Timber.tag(TAG).w("No local master key so not verifying")
Timber.tag(TAG).w("Master key from verifying device doesn't match: $masterKeyFromVerifyingDevice vs $localMasterKey") } ?: run {
throw RuntimeException("Master key from verifying device doesn't match") // set other device as verified anyway
} Timber.tag(TAG).i("Setting device $verifyingDeviceId as verified")
} ?: Timber.tag(TAG).i("No local master key") crypto.setDeviceVerification(DeviceTrustLevel(locallyVerified = true, crossSigningVerified = false), userId, verifyingDeviceId)
} ?: Timber.tag(TAG).i("No master key given by verifying device")
// request secrets from the verifying device Timber.tag(TAG).i("No master key given by verifying device")
Timber.tag(TAG).i("Requesting secrets from $verifyingDeviceId") }
session.sharedSecretStorageService().let { // request secrets from the verifying device
it.requestSecret(MASTER_KEY_SSSS_NAME, verifyingDeviceId) Timber.tag(TAG).i("Requesting secrets from $verifyingDeviceId")
it.requestSecret(SELF_SIGNING_KEY_SSSS_NAME, verifyingDeviceId)
it.requestSecret(USER_SIGNING_KEY_SSSS_NAME, verifyingDeviceId) session.sharedSecretStorageService().let {
it.requestSecret(KEYBACKUP_SECRET_SSSS_NAME, verifyingDeviceId) it.requestSecret(MASTER_KEY_SSSS_NAME, verifyingDeviceId)
it.requestSecret(SELF_SIGNING_KEY_SSSS_NAME, verifyingDeviceId)
it.requestSecret(USER_SIGNING_KEY_SSSS_NAME, verifyingDeviceId)
it.requestSecret(KEYBACKUP_SECRET_SSSS_NAME, verifyingDeviceId)
}
} else {
Timber.tag(TAG).i("Not doing verification")
} }
} }
@Throws(RendezvousError::class)
private suspend fun receive(): Payload? { private suspend fun receive(): Payload? {
val data = channel.receive() ?: return null val data = channel.receive() ?: return null
return adapter.fromJson(data.toString(Charsets.UTF_8)) val payload = try {
adapter.fromJson(data.toString(Charsets.UTF_8))
} catch (e: Exception) {
Timber.tag(TAG).w(e, "Failed to parse payload")
throw RendezvousError("Invalid payload received", RendezvousFailureReason.Unknown)
}
return payload
} }
private suspend fun send(payload: Payload) { private suspend fun send(payload: Payload) {
channel.send(adapter.toJson(payload).toByteArray(Charsets.UTF_8)) channel.send(adapter.toJson(payload).toByteArray(Charsets.UTF_8))
} }
suspend fun cancel(reason: RendezvousFailureReason) {
channel.cancel(reason)
}
suspend fun close() { suspend fun close() {
channel.close() channel.close()
} }

View File

@ -16,8 +16,7 @@
package org.matrix.android.sdk.api.rendezvous package org.matrix.android.sdk.api.rendezvous
import org.matrix.android.sdk.api.rendezvous.model.ECDHRendezvousCode import org.matrix.android.sdk.api.rendezvous.model.RendezvousError
import org.matrix.android.sdk.api.rendezvous.model.RendezvousIntent
/** /**
* Representation of a rendezvous channel such as that described by MSC3903. * Representation of a rendezvous channel such as that described by MSC3903.
@ -28,26 +27,25 @@ interface RendezvousChannel {
/** /**
* @returns the checksum/confirmation digits to be shown to the user * @returns the checksum/confirmation digits to be shown to the user
*/ */
@Throws(RendezvousError::class)
suspend fun connect(): String suspend fun connect(): String
/** /**
* Send a payload via the channel. * Send a payload via the channel.
* @param data payload to send * @param data payload to send
*/ */
@Throws(RendezvousError::class)
suspend fun send(data: ByteArray) suspend fun send(data: ByteArray)
/** /**
* Receive a payload from the channel. * Receive a payload from the channel.
* @returns the received payload * @returns the received payload
*/ */
@Throws(RendezvousError::class)
suspend fun receive(): ByteArray? suspend fun receive(): ByteArray?
/** /**
* @returns a representation of the channel that can be encoded in a QR or similar * @returns closes the channel and cleans up
*/ */
suspend fun close() suspend fun close()
// In future we probably want this to be a more generic RendezvousCode but it is suffice for now
suspend fun generateCode(intent: RendezvousIntent): ECDHRendezvousCode
suspend fun cancel(reason: RendezvousFailureReason)
} }

View File

@ -16,16 +16,17 @@
package org.matrix.android.sdk.api.rendezvous package org.matrix.android.sdk.api.rendezvous
enum class RendezvousFailureReason(val value: String, val canRetry: Boolean = true) { enum class RendezvousFailureReason(val canRetry: Boolean = true) {
UserDeclined("user_declined"), UserDeclined,
OtherDeviceNotSignedIn("other_device_not_signed_in"), OtherDeviceNotSignedIn,
OtherDeviceAlreadySignedIn("other_device_already_signed_in"), OtherDeviceAlreadySignedIn,
Unknown("unknown"), Unknown,
Expired("expired"), Expired,
UserCancelled("user_cancelled"), UserCancelled,
InvalidCode("invalid_code"), InvalidCode,
UnsupportedAlgorithm("unsupported_algorithm", false), UnsupportedAlgorithm(false),
DataMismatch("data_mismatch"), UnsupportedTransport(false),
UnsupportedTransport("unsupported_transport", false), UnsupportedHomeserver(false),
HomeserverLacksSupport("homeserver_lacks_support", false) ProtocolError,
E2EESecurityIssue(false)
} }

View File

@ -17,13 +17,16 @@
package org.matrix.android.sdk.api.rendezvous package org.matrix.android.sdk.api.rendezvous
import okhttp3.MediaType import okhttp3.MediaType
import org.matrix.android.sdk.api.rendezvous.model.RendezvousError
import org.matrix.android.sdk.api.rendezvous.model.RendezvousTransportDetails import org.matrix.android.sdk.api.rendezvous.model.RendezvousTransportDetails
interface RendezvousTransport { interface RendezvousTransport {
var ready: Boolean var ready: Boolean
var onCancelled: ((reason: RendezvousFailureReason) -> Unit)? @Throws(RendezvousError::class)
suspend fun details(): RendezvousTransportDetails suspend fun details(): RendezvousTransportDetails
@Throws(RendezvousError::class)
suspend fun send(contentType: MediaType, data: ByteArray) suspend fun send(contentType: MediaType, data: ByteArray)
@Throws(RendezvousError::class)
suspend fun receive(): ByteArray? suspend fun receive(): ByteArray?
suspend fun cancel(reason: RendezvousFailureReason) suspend fun close()
} }

View File

@ -89,13 +89,14 @@ class ECDHRendezvousChannel(override var transport: RendezvousTransport, theirPu
ourPublicKey = Base64.decode(olmSAS!!.publicKey, Base64.NO_WRAP) ourPublicKey = Base64.decode(olmSAS!!.publicKey, Base64.NO_WRAP)
} }
@Throws(RendezvousError::class)
override suspend fun connect(): String { override suspend fun connect(): String {
olmSAS ?.let { olmSAS -> olmSAS ?.let { olmSAS ->
val isInitiator = theirPublicKey == null val isInitiator = theirPublicKey == null
if (isInitiator) { if (isInitiator) {
Timber.tag(TAG).i("Waiting for other device to send their public key") Timber.tag(TAG).i("Waiting for other device to send their public key")
val res = this.receiveAsPayload() ?: throw RuntimeException("No reply from other device") val res = this.receiveAsPayload() ?: throw RendezvousError("No reply from other device", RendezvousFailureReason.ProtocolError)
if (res.key == null) { if (res.key == null) {
throw RendezvousError( throw RendezvousError(
@ -137,7 +138,7 @@ class ECDHRendezvousChannel(override var transport: RendezvousTransport, theirPu
override suspend fun send(data: ByteArray) { override suspend fun send(data: ByteArray) {
if (aesKey == null) { if (aesKey == null) {
throw RuntimeException("Shared secret not established") throw IllegalStateException("Shared secret not established")
} }
send(encrypt(data)) send(encrypt(data))
} }
@ -150,31 +151,12 @@ class ECDHRendezvousChannel(override var transport: RendezvousTransport, theirPu
override suspend fun receive(): ByteArray? { override suspend fun receive(): ByteArray? {
if (aesKey == null) { if (aesKey == null) {
throw RuntimeException("Shared secret not established") throw IllegalStateException("Shared secret not established")
} }
val payload = receiveAsPayload() ?: return null val payload = receiveAsPayload() ?: return null
return decrypt(payload) return decrypt(payload)
} }
override suspend fun generateCode(intent: RendezvousIntent): ECDHRendezvousCode {
return ECDHRendezvousCode(
intent,
rendezvous = ECDHRendezvous(
transport.details() as SimpleHttpRendezvousTransportDetails,
SecureRendezvousChannelAlgorithm.ECDH_V1,
key = Base64.encodeToString(ourPublicKey, Base64.NO_WRAP)
)
)
}
override suspend fun cancel(reason: RendezvousFailureReason) {
try {
transport.cancel(reason)
} finally {
close()
}
}
override suspend fun close() { override suspend fun close() {
olmSAS ?.let { olmSAS ?.let {
synchronized(it) { synchronized(it) {
@ -183,6 +165,7 @@ class ECDHRendezvousChannel(override var transport: RendezvousTransport, theirPu
olmSAS = null olmSAS = null
} }
} }
transport.close()
} }
private fun encrypt(plainText: ByteArray): ECDHPayload { private fun encrypt(plainText: ByteArray): ECDHPayload {

View File

@ -26,5 +26,11 @@ enum class Outcome(val value: String) {
DECLINED("declined"), DECLINED("declined"),
@Json(name = "unsupported") @Json(name = "unsupported")
UNSUPPORTED("unsupported") UNSUPPORTED("unsupported"),
@Json(name = "verified")
VERIFIED("verified"),
@Json(name = "e2ee_security_error")
E2EE_SECURITY_ERROR("e2ee_security_error")
} }

View File

@ -18,4 +18,4 @@ package org.matrix.android.sdk.api.rendezvous.model
import org.matrix.android.sdk.api.rendezvous.RendezvousFailureReason import org.matrix.android.sdk.api.rendezvous.RendezvousFailureReason
class RendezvousError(val description: String, val reason: RendezvousFailureReason) : RuntimeException(description) class RendezvousError(val description: String, val reason: RendezvousFailureReason) : Exception(description)

View File

@ -23,6 +23,7 @@ import okhttp3.RequestBody.Companion.toRequestBody
import org.matrix.android.sdk.api.logger.LoggerTag import org.matrix.android.sdk.api.logger.LoggerTag
import org.matrix.android.sdk.api.rendezvous.RendezvousFailureReason import org.matrix.android.sdk.api.rendezvous.RendezvousFailureReason
import org.matrix.android.sdk.api.rendezvous.RendezvousTransport import org.matrix.android.sdk.api.rendezvous.RendezvousTransport
import org.matrix.android.sdk.api.rendezvous.model.RendezvousError
import org.matrix.android.sdk.api.rendezvous.model.RendezvousTransportDetails import org.matrix.android.sdk.api.rendezvous.model.RendezvousTransportDetails
import org.matrix.android.sdk.api.rendezvous.model.SimpleHttpRendezvousTransportDetails import org.matrix.android.sdk.api.rendezvous.model.SimpleHttpRendezvousTransportDetails
import timber.log.Timber import timber.log.Timber
@ -32,7 +33,7 @@ import java.util.Date
/** /**
* Implementation of the Simple HTTP transport MSC3886: https://github.com/matrix-org/matrix-spec-proposals/pull/3886 * Implementation of the Simple HTTP transport MSC3886: https://github.com/matrix-org/matrix-spec-proposals/pull/3886
*/ */
class SimpleHttpRendezvousTransport(override var onCancelled: ((reason: RendezvousFailureReason) -> Unit)?, rendezvousUri: String?) : RendezvousTransport { class SimpleHttpRendezvousTransport(rendezvousUri: String?) : RendezvousTransport {
companion object { companion object {
private val TAG = LoggerTag(SimpleHttpRendezvousTransport::class.java.simpleName, LoggerTag.RENDEZVOUS).value private val TAG = LoggerTag(SimpleHttpRendezvousTransport::class.java.simpleName, LoggerTag.RENDEZVOUS).value
} }
@ -55,7 +56,7 @@ class SimpleHttpRendezvousTransport(override var onCancelled: ((reason: Rendezvo
override suspend fun send(contentType: MediaType, data: ByteArray) { override suspend fun send(contentType: MediaType, data: ByteArray) {
if (cancelled) { if (cancelled) {
return throw IllegalStateException("Rendezvous cancelled")
} }
val method = if (uri != null) "PUT" else "POST" val method = if (uri != null) "PUT" else "POST"
@ -75,9 +76,7 @@ class SimpleHttpRendezvousTransport(override var onCancelled: ((reason: Rendezvo
val response = httpClient.newCall(request.build()).execute() val response = httpClient.newCall(request.build()).execute()
if (response.code == 404) { if (response.code == 404) {
// we set to unknown and the cancel method will rewrite the reason to expired if applicable throw get404Error()
cancel(RendezvousFailureReason.Unknown)
return
} }
etag = response.header("etag") etag = response.header("etag")
@ -98,12 +97,12 @@ class SimpleHttpRendezvousTransport(override var onCancelled: ((reason: Rendezvo
} }
override suspend fun receive(): ByteArray? { override suspend fun receive(): ByteArray? {
if (cancelled) {
throw IllegalStateException("Rendezvous cancelled")
}
val uri = uri ?: throw IllegalStateException("Rendezvous not set up") val uri = uri ?: throw IllegalStateException("Rendezvous not set up")
val httpClient = okhttp3.OkHttpClient.Builder().build() val httpClient = okhttp3.OkHttpClient.Builder().build()
while (true) { while (true) {
if (cancelled) {
return null
}
Timber.tag(TAG).i("Polling: $uri after etag $etag") Timber.tag(TAG).i("Polling: $uri after etag $etag")
val request = Request.Builder() val request = Request.Builder()
.url(uri) .url(uri)
@ -118,9 +117,7 @@ class SimpleHttpRendezvousTransport(override var onCancelled: ((reason: Rendezvo
try { try {
// expired // expired
if (response.code == 404) { if (response.code == 404) {
// we set to unknown and the cancel method will rewrite the reason to expired if applicable throw get404Error()
cancel(RendezvousFailureReason.Unknown)
return null
} }
// rely on server expiring the channel rather than checking ourselves // rely on server expiring the channel rather than checking ourselves
@ -145,31 +142,27 @@ class SimpleHttpRendezvousTransport(override var onCancelled: ((reason: Rendezvo
} }
} }
override suspend fun cancel(reason: RendezvousFailureReason) { private fun get404Error(): RendezvousError {
var mappedReason = reason return if (expiresAt != null && Date() > expiresAt)
Timber.tag(TAG).i("$expiresAt") RendezvousError("Expired", RendezvousFailureReason.Expired)
if (mappedReason == RendezvousFailureReason.Unknown && else
expiresAt != null && Date() > expiresAt RendezvousError("Received unexpected 404", RendezvousFailureReason.Unknown)
) { }
mappedReason = RendezvousFailureReason.Expired
}
override suspend fun close() {
cancelled = true cancelled = true
ready = false ready = false
onCancelled ?.let { it(mappedReason) }
if (mappedReason == RendezvousFailureReason.UserDeclined) { uri ?.let {
uri ?.let { try {
try { val httpClient = okhttp3.OkHttpClient.Builder().build()
val httpClient = okhttp3.OkHttpClient.Builder().build() val request = Request.Builder()
val request = Request.Builder() .url(it)
.url(it) .delete()
.delete() .build()
.build() httpClient.newCall(request).execute()
httpClient.newCall(request).execute() } catch (e: Throwable) {
} catch (e: Exception) { Timber.tag(TAG).w(e, "Failed to delete channel")
Timber.tag(TAG).w(e, "Failed to delete channel")
}
} }
} }
} }

View File

@ -70,8 +70,14 @@ class QrCodeLoginStatusFragment : VectorBaseFragment<FragmentQrCodeLoginStatusBi
return when (reason) { return when (reason) {
RendezvousFailureReason.UnsupportedAlgorithm, RendezvousFailureReason.UnsupportedAlgorithm,
RendezvousFailureReason.UnsupportedTransport -> getString(R.string.qr_code_login_header_failed_device_is_not_supported_description) RendezvousFailureReason.UnsupportedTransport -> getString(R.string.qr_code_login_header_failed_device_is_not_supported_description)
RendezvousFailureReason.UnsupportedHomeserver -> getString(R.string.qr_code_login_header_failed_homeserver_is_not_supported_description)
RendezvousFailureReason.Expired -> getString(R.string.qr_code_login_header_failed_timeout_description) RendezvousFailureReason.Expired -> getString(R.string.qr_code_login_header_failed_timeout_description)
RendezvousFailureReason.UserDeclined -> getString(R.string.qr_code_login_header_failed_denied_description) RendezvousFailureReason.UserDeclined -> getString(R.string.qr_code_login_header_failed_denied_description)
RendezvousFailureReason.E2EESecurityIssue -> getString(R.string.qr_code_login_header_failed_e2ee_security_issue_description)
RendezvousFailureReason.OtherDeviceAlreadySignedIn -> getString(R.string.qr_code_login_header_failed_other_device_already_signed_in_description)
RendezvousFailureReason.OtherDeviceNotSignedIn -> getString(R.string.qr_code_login_header_failed_other_device_not_signed_in_description)
RendezvousFailureReason.InvalidCode -> getString(R.string.qr_code_login_header_failed_invalid_qr_code_description)
RendezvousFailureReason.UserCancelled -> getString(R.string.qr_code_login_header_failed_user_cancelled_description)
else -> getString(R.string.qr_code_login_header_failed_other_description) else -> getString(R.string.qr_code_login_header_failed_other_description)
} }
} }

View File

@ -30,6 +30,7 @@ import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.auth.AuthenticationService import org.matrix.android.sdk.api.auth.AuthenticationService
import org.matrix.android.sdk.api.rendezvous.Rendezvous import org.matrix.android.sdk.api.rendezvous.Rendezvous
import org.matrix.android.sdk.api.rendezvous.RendezvousFailureReason import org.matrix.android.sdk.api.rendezvous.RendezvousFailureReason
import org.matrix.android.sdk.api.rendezvous.model.RendezvousError
import timber.log.Timber import timber.log.Timber
class QrCodeLoginViewModel @AssistedInject constructor( class QrCodeLoginViewModel @AssistedInject constructor(
@ -38,14 +39,15 @@ class QrCodeLoginViewModel @AssistedInject constructor(
private val activeSessionHolder: ActiveSessionHolder, private val activeSessionHolder: ActiveSessionHolder,
private val configureAndStartSessionUseCase: ConfigureAndStartSessionUseCase private val configureAndStartSessionUseCase: ConfigureAndStartSessionUseCase
) : VectorViewModel<QrCodeLoginViewState, QrCodeLoginAction, QrCodeLoginViewEvents>(initialState) { ) : VectorViewModel<QrCodeLoginViewState, QrCodeLoginAction, QrCodeLoginViewEvents>(initialState) {
val TAG: String = QrCodeLoginViewModel::class.java.simpleName
@AssistedFactory @AssistedFactory
interface Factory : MavericksAssistedViewModelFactory<QrCodeLoginViewModel, QrCodeLoginViewState> { interface Factory : MavericksAssistedViewModelFactory<QrCodeLoginViewModel, QrCodeLoginViewState> {
override fun create(initialState: QrCodeLoginViewState): QrCodeLoginViewModel override fun create(initialState: QrCodeLoginViewState): QrCodeLoginViewModel
} }
companion object : MavericksViewModelFactory<QrCodeLoginViewModel, QrCodeLoginViewState> by hiltMavericksViewModelFactory() companion object : MavericksViewModelFactory<QrCodeLoginViewModel, QrCodeLoginViewState> by hiltMavericksViewModelFactory() {
val TAG: String = QrCodeLoginViewModel::class.java.simpleName
}
override fun handle(action: QrCodeLoginAction) { override fun handle(action: QrCodeLoginAction) {
when (action) { when (action) {
@ -71,9 +73,14 @@ class QrCodeLoginViewModel @AssistedInject constructor(
private fun handleOnQrCodeScanned(action: QrCodeLoginAction.OnQrCodeScanned) { private fun handleOnQrCodeScanned(action: QrCodeLoginAction.OnQrCodeScanned) {
Timber.tag(TAG).d("Scanned code: ${action.qrCode}") Timber.tag(TAG).d("Scanned code: ${action.qrCode}")
val rendezvous = Rendezvous.buildChannelFromCode(action.qrCode) { reason -> val rendezvous = try { Rendezvous.buildChannelFromCode(action.qrCode) } catch (t: Throwable) {
Timber.tag(TAG).d("Rendezvous cancelled: $reason") Timber.tag(TAG).e(t, "Error occurred during sign in")
onFailed(reason) if (t is RendezvousError) {
onFailed(t.reason)
} else {
onFailed(RendezvousFailureReason.Unknown)
}
return
} }
setState { setState {
@ -103,9 +110,13 @@ class QrCodeLoginViewModel @AssistedInject constructor(
_viewEvents.post(QrCodeLoginViewEvents.NavigateToHomeScreen) _viewEvents.post(QrCodeLoginViewEvents.NavigateToHomeScreen)
} }
} }
} catch (failure: Throwable) { } catch (t: Throwable) {
Timber.tag(TAG).e(failure, "Error occurred during sign in") Timber.tag(TAG).e(t, "Error occurred during sign in")
onFailed(RendezvousFailureReason.Unknown) if (t is RendezvousError) {
onFailed(t.reason)
} else {
onFailed(RendezvousFailureReason.Unknown)
}
} }
} }
} }