matrix-sdk 0.19.0

A high level Matrix client-server library.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
// Copyright 2024 The Matrix.org Foundation C.I.C.
//
// 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.

//! Types for the QR code login support defined in [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108).
//!
//! Please note, QR code logins are only supported when using OAuth 2.0 as the
//! authentication mechanism, native Matrix authentication does not support it.
//!
//! This currently only implements the case where the new device is scanning the
//! QR code. To log in using a QR code, please take a look at the
//! [`OAuth::login_with_qr_code()`] method.

use std::sync::Arc;

use as_variant::as_variant;
pub use matrix_sdk_base::crypto::types::qr_login::{
    LoginQrCodeDecodeError, Msc4108IntentData, QrCodeData, QrCodeIntent, QrCodeIntentData,
};
use matrix_sdk_base::crypto::{SecretImportError, store::SecretsBundleExportError};
pub use oauth2::{
    ConfigurationError, DeviceCodeErrorResponse, DeviceCodeErrorResponseType, HttpClientError,
    RequestTokenError, StandardErrorResponse,
    basic::{BasicErrorResponse, BasicRequestTokenError},
};
use ruma::api::error::ErrorKind;
use thiserror::Error;
use tokio::sync::Mutex;
use url::Url;
pub use vodozemac::ecies::{Error as EciesError, MessageDecodeError};

mod grant;
mod login;
mod messages;
mod rendezvous_channel;
mod secure_channel;

pub use self::{
    grant::{GrantLoginProgress, GrantLoginWithGeneratedQrCode, GrantLoginWithScannedQrCode},
    login::{LoginProgress, LoginWithGeneratedQrCode, LoginWithQrCode},
    messages::{LoginFailureReason, LoginProtocolType, QrAuthMessage},
};
use super::CrossProcessRefreshLockError;
#[cfg(doc)]
use super::OAuth;
use crate::HttpError;

/// The error type for failures while trying to log in a new device using a QR
/// code.
#[derive(Debug, Error)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Error), uniffi(flat_error))]
pub enum QRCodeLoginError {
    /// An error happened while we were communicating with the OAuth 2.0
    /// authorization server.
    #[error(transparent)]
    OAuth(#[from] DeviceAuthorizationOAuthError),

    /// The other device has signaled to us that the login has failed.
    #[error("The login failed, reason: {reason}")]
    LoginFailure {
        /// The reason, as signaled by the other device, for the login failure.
        reason: LoginFailureReason,
        /// The homeserver that we attempted to log in to.
        homeserver: Option<Url>,
    },

    /// An unexpected message was received from the other device.
    #[error("We have received an unexpected message, expected: {expected}, got {received:?}")]
    UnexpectedMessage {
        /// The message we expected.
        expected: &'static str,
        /// The message we received instead.
        received: Box<QrAuthMessage>,
    },

    /// An error happened while exchanging messages with the other device.
    #[error(transparent)]
    SecureChannel(SecureChannelError),

    /// The rendezvous session was not found and might have expired.
    #[error("The rendezvous session was not found and might have expired")]
    NotFound,

    /// The cross-process refresh lock failed to be initialized.
    #[error(transparent)]
    CrossProcessRefreshLock(#[from] CrossProcessRefreshLockError),

    /// An error happened while we were trying to discover our user and device
    /// ID, after we have acquired an access token from the OAuth 2.0
    /// authorization server.
    #[error(transparent)]
    UserIdDiscovery(HttpError),

    /// We failed to set the session tokens after we figured out our device and
    /// user IDs.
    #[error(transparent)]
    SessionTokens(crate::Error),

    /// The device keys failed to be uploaded after we successfully logged in.
    #[error(transparent)]
    DeviceKeyUpload(crate::Error),

    /// The secrets bundle we received from the existing device failed to be
    /// imported.
    #[error(transparent)]
    SecretImport(#[from] SecretImportError),

    /// The other party told us to use a different homeserver but we failed to
    /// reset the server URL.
    #[error(transparent)]
    ServerReset(crate::Error),
}

impl From<SecureChannelError> for QRCodeLoginError {
    fn from(e: SecureChannelError) -> Self {
        match e {
            SecureChannelError::RendezvousChannel(ref http_error) => {
                if let Some(ErrorKind::NotFound) = http_error.client_api_error_kind() {
                    return Self::NotFound;
                }
                Self::SecureChannel(e)
            }
            e => Self::SecureChannel(e),
        }
    }
}

/// The error type for failures while trying to grant log in to a new device
/// using a QR code.
#[derive(Debug, Error)]
pub enum QRCodeGrantLoginError {
    /// Secrets backup not set up.
    #[error("Secrets backup not set up")]
    MissingSecretsBackup(Option<SecretsBundleExportError>),

    /// The check code was incorrect.
    #[error("The check code was incorrect")]
    InvalidCheckCode,

    /// The rendezvous session was not found and might have expired.
    #[error("The rendezvous session was not found and might have expired")]
    NotFound,

    /// Auth handshake error.
    #[error("Auth handshake error: {0}")]
    Unknown(String),

    /// Unsupported protocol.
    #[error("Unsupported protocol: {0}")]
    UnsupportedProtocol(LoginProtocolType),

    /// The requested device ID is already in use.
    #[error("The requested device ID is already in use")]
    DeviceIDAlreadyInUse,

    /// The requested device was not returned by the homeserver.
    #[error("The requested device was not returned by the homeserver")]
    DeviceNotFound,

    /// An error happened while exchanging messages with the other device.
    #[error(transparent)]
    SecureChannel(SecureChannelError),

    /// An unexpected message was received from the other device.
    #[error("We have received an unexpected message, expected: {expected}, got {received:?}")]
    UnexpectedMessage {
        /// The message we expected.
        expected: &'static str,
        /// The message we received instead.
        received: Box<QrAuthMessage>,
    },

    /// The other device has signaled to us that the login has failed.
    #[error("The login failed, reason: {reason}")]
    LoginFailure {
        /// The reason, as signaled by the other device, for the login failure.
        reason: LoginFailureReason,
    },
}

impl From<SecureChannelError> for QRCodeGrantLoginError {
    fn from(e: SecureChannelError) -> Self {
        match e {
            SecureChannelError::RendezvousChannel(ref http_error) => {
                if let Some(ErrorKind::NotFound) = http_error.client_api_error_kind() {
                    return Self::NotFound;
                }
                Self::SecureChannel(e)
            }
            SecureChannelError::InvalidCheckCode => Self::InvalidCheckCode,
            e => Self::SecureChannel(e),
        }
    }
}

impl From<SecretsBundleExportError> for QRCodeGrantLoginError {
    fn from(e: SecretsBundleExportError) -> Self {
        Self::MissingSecretsBackup(Some(e))
    }
}

/// Error type describing failures in the interaction between the device
/// attempting to log in and the OAuth 2.0 authorization server.
#[derive(Debug, Error)]
pub enum DeviceAuthorizationOAuthError {
    /// A generic OAuth 2.0 error happened while we were attempting to register
    /// the device with the OAuth 2.0 authorization server.
    #[error(transparent)]
    OAuth(#[from] crate::authentication::oauth::OAuthError),

    /// The OAuth 2.0 server doesn't support the device authorization grant.
    #[error("OAuth 2.0 server doesn't support the device authorization grant")]
    NoDeviceAuthorizationEndpoint,

    /// An error happened while we attempted to request a device authorization
    /// from the OAuth 2.0 authorization server.
    #[error(transparent)]
    DeviceAuthorization(#[from] BasicRequestTokenError<HttpClientError<reqwest::Error>>),

    /// An error happened while waiting for the access token to be issued and
    /// sent to us by the OAuth 2.0 authorization server.
    #[error(transparent)]
    RequestToken(
        #[from] RequestTokenError<HttpClientError<reqwest::Error>, DeviceCodeErrorResponse>,
    ),
}

impl DeviceAuthorizationOAuthError {
    /// If the [`DeviceAuthorizationOAuthError`] is of the
    /// [`DeviceCodeErrorResponseType`] error variant, return it.
    pub fn as_request_token_error(&self) -> Option<&DeviceCodeErrorResponseType> {
        let error = as_variant!(self, DeviceAuthorizationOAuthError::RequestToken)?;
        let request_token_error = as_variant!(error, RequestTokenError::ServerResponse)?;

        Some(request_token_error.error())
    }
}

/// Error type for failures in when receiving or sending messages over the
/// secure channel.
#[derive(Debug, Error)]
pub enum SecureChannelError {
    /// A message we received over the secure channel was not a valid UTF-8
    /// encoded string.
    #[error(transparent)]
    Utf8(#[from] std::str::Utf8Error),

    /// A message has failed to be decrypted.
    #[error(transparent)]
    Ecies(#[from] EciesError),

    /// A received message has failed to be decoded.
    #[error(transparent)]
    MessageDecode(#[from] MessageDecodeError),

    /// A message couldn't be deserialized from JSON.
    #[error(transparent)]
    Json(#[from] serde_json::Error),

    /// The secure channel failed to be established because it received an
    /// unexpected message.
    #[error(
        "The secure channel setup has received an unexpected message, expected: {expected}, got {received}"
    )]
    SecureChannelMessage {
        /// The secure channel message we expected.
        expected: &'static str,
        /// The secure channel message we received instead.
        received: String,
    },

    /// The secure channel could not have been established, the check code was
    /// invalid.
    #[error("The secure channel could not have been established, the check code was invalid")]
    InvalidCheckCode,

    /// An error happened in the underlying rendezvous channel.
    #[error("Error in the rendezvous channel: {0:?}")]
    RendezvousChannel(#[from] HttpError),

    /// Both devices have advertised the same intent in the login attempt, i.e.
    /// both sides claim to be a new device.
    #[error(
        "The secure channel could not have been established, \
         the two devices have the same login intent"
    )]
    InvalidIntent,

    /// The secure channel could not have been established, the check code
    /// cannot be received.
    #[error(
        "The secure channel could not have been established, \
         the check code cannot be received"
    )]
    CannotReceiveCheckCode,

    #[error("The QR code specifies an unsupported protocol version")]
    /// The QR code specifies an unsupported protocol version.
    UnsupportedQrCodeType,
}

/// Metadata to be used with [`LoginProgress::EstablishingSecureChannel`]
/// or [`GrantLoginProgress::EstablishingSecureChannel`] when
/// this device is the one scanning the QR code.
///
/// We have established the secure channel, but we need to let the other
/// side know about the check code so they can verify that the secure
/// channel is indeed secure.
#[derive(Clone, Debug)]
pub struct QrProgress {
    /// The check code we need to, out of band, send to the other device.
    pub check_code: u8,
}

/// Metadata to be used with [`LoginProgress::EstablishingSecureChannel`] and
/// [`GrantLoginProgress::EstablishingSecureChannel`] when this device is the
/// one generating the QR code.
///
/// We have established the secure channel, but we need to let the
/// other device know about the [`QrCodeData`] so they can connect to the
/// channel and let us know about the check code so we can verify that the
/// channel is indeed secure.
#[derive(Clone, Debug)]
pub enum GeneratedQrProgress {
    /// The QR code has been created and this device is waiting for the other
    /// device to scan it.
    QrReady(QrCodeData),
    /// The QR code has been scanned by the other device and this device is
    /// waiting for the user to put in the check code displayed on the
    /// other device.
    QrScanned(CheckCodeSender),
}

/// A oneshot sender used to send the check code back to the device that
/// generated the QR code.
pub type CheckCodeSender = CloneableSender<u8>;

impl CheckCodeSender {
    /// Send the check code.
    ///
    /// Calling this method more than once will result in an error.
    ///
    /// # Arguments
    ///
    /// * `check_code` - The check code in digits representation.
    pub async fn send(&self, check_code: u8) -> Result<(), SenderError> {
        self.send_impl(check_code).await
    }
}

/// The internal message of the [`ContinuationMessageSender`] to either continue
/// the login granting process or to cancel it.
#[derive(Clone, Copy, Debug)]
pub(crate) enum ContinuationMessage {
    Confirm,
    Cancel,
}

/// Struct used to let the QR code granting logic know that it can continue with
/// the process since applications might suspend things while the verification
/// URI is open.
#[derive(Clone, Debug)]
pub struct ContinuationMessageSender(CloneableSender<ContinuationMessage>);

impl ContinuationMessageSender {
    /// Confirm the continuation of the login granting process.
    pub async fn confirm(&self) -> Result<(), SenderError> {
        self.0.send_impl(ContinuationMessage::Confirm).await
    }

    /// Cancel the login granting process.
    pub async fn cancel(&self) -> Result<(), SenderError> {
        self.0.send_impl(ContinuationMessage::Cancel).await
    }
}

/// A oneshot sender we are able to clone so we can put it into a
/// [`SharedObservable`](eyeball::SharedObservable).
#[derive(Clone, Debug)]
pub struct CloneableSender<T> {
    inner: Arc<Mutex<Option<tokio::sync::oneshot::Sender<T>>>>,
}

impl<T> CloneableSender<T> {
    pub(crate) fn new(tx: tokio::sync::oneshot::Sender<T>) -> Self {
        Self { inner: Arc::new(Mutex::new(Some(tx))) }
    }

    async fn send_impl(&self, message: T) -> Result<(), SenderError> {
        match self.inner.lock().await.take() {
            Some(tx) => tx.send(message).map_err(|_| SenderError::CannotSend),
            None => Err(SenderError::AlreadySent),
        }
    }
}

/// Possible errors when calling [`CloneableSender::send`].
#[derive(Debug, thiserror::Error)]
pub enum SenderError {
    /// The message has already been sent.
    #[error("message already sent.")]
    AlreadySent,
    /// The message cannot be sent.
    #[error("message cannot be sent.")]
    CannotSend,
}

#[cfg(all(test, not(target_family = "wasm")))]
mod tests {
    use matrix_sdk_test::async_test;
    use serde_json::json;
    use wiremock::{
        Mock, ResponseTemplate,
        matchers::{method, path},
    };

    use crate::test_utils::mocks::MatrixMockServer;

    #[async_test]
    async fn test_msc_4388_rendezvous_server_supported() {
        const URL: &str = "/_matrix/client/unstable/io.element.msc4388/rendezvous";

        let server = MatrixMockServer::new().await;
        let client = server.client_builder().logged_in_with_oauth().build().await;

        {
            let _discover_guard = server
                .server()
                .register_as_scoped(
                    Mock::given(method("GET"))
                        .and(path(URL))
                        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                            "create_available": true,
                        })))
                        .expect(1),
                )
                .await;

            let supported = client
                .oauth()
                .msc_4388_rendezvous_server_supported()
                .await
                .expect("We should be able to check if the rendezvous server is supported");

            assert!(supported, "The rendezvous server should be supported");
        }

        {
            let _discover_guard = server
                .server()
                .register_as_scoped(
                    Mock::given(method("GET"))
                        .and(path(URL))
                        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                            "create_available": false,
                        })))
                        .expect(1),
                )
                .await;

            let supported = client
                .oauth()
                .msc_4388_rendezvous_server_supported()
                .await
                .expect("We should be able to check if the rendezvous server is supported");

            assert!(
                !supported,
                "The rendezvous server should not be supported, because create_available is false"
            );
        }

        {
            let _discover_guard = server
                .server()
                .register_as_scoped(
                    Mock::given(method("GET"))
                        .and(path(URL))
                        .respond_with(ResponseTemplate::new(404))
                        .expect(1),
                )
                .await;

            let supported = client
                .oauth()
                .msc_4388_rendezvous_server_supported()
                .await
                .expect("We should be able to check if the rendezvous server is supported");

            assert!(
                !supported,
                "The rendezvous server should not be supported if we receive a 404 response"
            );
        }

        {
            let _discover_guard = server
                .server()
                .register_as_scoped(
                    Mock::given(method("GET"))
                        .and(path(URL))
                        .respond_with(ResponseTemplate::new(403))
                        .expect(1),
                )
                .await;

            let supported = client
                .oauth()
                .msc_4388_rendezvous_server_supported()
                .await
                .expect("We should be able to check if the rendezvous server is supported");

            assert!(
                !supported,
                "The rendezvous server should not be supported if we receive a 403 response"
            );
        }

        {
            let _discover_guard = server
                .server()
                .register_as_scoped(
                    Mock::given(method("GET"))
                        .and(path(URL))
                        .respond_with(ResponseTemplate::new(500))
                        .expect(1),
                )
                .await;

            client
                .oauth()
                .msc_4388_rendezvous_server_supported()
                .await
                .expect_err("We should return an error if the homeserver can't tell us if the endpoint is supported or not");
        }
    }
}