Skip to main content

matrix_sdk/authentication/oauth/qrcode/
mod.rs

1// Copyright 2024 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Types for the QR code login support defined in [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108).
16//!
17//! Please note, QR code logins are only supported when using OAuth 2.0 as the
18//! authentication mechanism, native Matrix authentication does not support it.
19//!
20//! This currently only implements the case where the new device is scanning the
21//! QR code. To log in using a QR code, please take a look at the
22//! [`OAuth::login_with_qr_code()`] method.
23
24use std::sync::Arc;
25
26pub use matrix_sdk_base::crypto::types::qr_login::{
27    LoginQrCodeDecodeError, Msc4108IntentData, QrCodeData, QrCodeIntent, QrCodeIntentData,
28};
29use matrix_sdk_base::crypto::{
30    SecretImportError,
31    store::SecretsBundleExportError,
32    types::qr_login::{InvalidLengthError, QrCodeCreationError},
33};
34pub use oauth2::{
35    ConfigurationError, DeviceCodeErrorResponse, DeviceCodeErrorResponseType, HttpClientError,
36    RequestTokenError, StandardErrorResponse,
37    basic::{BasicErrorResponse, BasicRequestTokenError},
38};
39use ruma::api::error::ErrorKind;
40use thiserror::Error;
41use tokio::sync::Mutex;
42pub use vodozemac::{
43    ecies::{Error as EciesError, MessageDecodeError as EciesMessageDecodeError},
44    hpke::{Error as HpkeError, MessageDecodeError as HpkeMessageDecodeError},
45};
46
47mod grant;
48mod login;
49mod messages;
50mod rendezvous_channel;
51mod secure_channel;
52
53pub use self::{
54    grant::{GrantLoginProgress, GrantLoginWithGeneratedQrCode, GrantLoginWithScannedQrCode},
55    login::{LoginProgress, LoginWithGeneratedQrCode, LoginWithQrCode},
56    messages::{
57        AuthorizationGrant, LoginFailureReason, LoginProtocolData, LoginProtocolType,
58        QrAuthMessage, UnknownLoginProtocol,
59    },
60};
61use super::CrossProcessRefreshLockError;
62#[cfg(doc)]
63use super::OAuth;
64pub use super::error::DeviceAuthorizationOAuthError;
65use crate::HttpError;
66
67/// The error type for failures while trying to log in a new device using a QR
68/// code.
69#[derive(Debug, Error)]
70#[cfg_attr(feature = "uniffi", derive(uniffi::Error), uniffi(flat_error))]
71pub enum QRCodeLoginError {
72    /// An error happened while we were communicating with the OAuth 2.0
73    /// authorization server.
74    #[error(transparent)]
75    OAuth(#[from] DeviceAuthorizationOAuthError),
76
77    /// The other device has signaled to us that the login has failed.
78    #[error("The login failed, reason: {reason}")]
79    LoginFailure {
80        /// The reason, as signaled by the other device, for the login failure.
81        reason: LoginFailureReason,
82        /// The homeserver the other device suggested we use, either as a
83        /// server name or as a homeserver URL.
84        homeserver: Option<String>,
85    },
86
87    /// An unexpected message was received from the other device.
88    #[error("We have received an unexpected message, expected: {expected}, got {received:?}")]
89    UnexpectedMessage {
90        /// The message we expected.
91        expected: &'static str,
92        /// The message we received instead.
93        received: Box<QrAuthMessage>,
94    },
95
96    /// An error happened while exchanging messages with the other device.
97    #[error(transparent)]
98    SecureChannel(SecureChannelError),
99
100    /// The rendezvous session was not found and might have expired.
101    #[error("The rendezvous session was not found and might have expired")]
102    NotFound,
103
104    /// The cross-process refresh lock failed to be initialized.
105    #[error(transparent)]
106    CrossProcessRefreshLock(#[from] CrossProcessRefreshLockError),
107
108    /// An error happened while we were trying to discover our user and device
109    /// ID, after we have acquired an access token from the OAuth 2.0
110    /// authorization server.
111    #[error(transparent)]
112    UserIdDiscovery(HttpError),
113
114    /// We failed to set the session tokens after we figured out our device and
115    /// user IDs.
116    #[error(transparent)]
117    SessionTokens(crate::Error),
118
119    /// The device keys failed to be uploaded after we successfully logged in.
120    #[error(transparent)]
121    DeviceKeyUpload(crate::Error),
122
123    /// The secrets bundle we received from the existing device failed to be
124    /// imported.
125    #[error(transparent)]
126    SecretImport(#[from] SecretImportError),
127
128    /// The other party told us to use a different homeserver but we failed to
129    /// reset the server URL.
130    #[error(transparent)]
131    ServerReset(crate::Error),
132}
133
134impl From<SecureChannelError> for QRCodeLoginError {
135    fn from(e: SecureChannelError) -> Self {
136        match e {
137            SecureChannelError::RendezvousChannel(ref http_error) => {
138                if let Some(ErrorKind::NotFound) = http_error.client_api_error_kind() {
139                    return Self::NotFound;
140                }
141                Self::SecureChannel(e)
142            }
143            e => Self::SecureChannel(e),
144        }
145    }
146}
147
148/// The error type for failures while trying to grant log in to a new device
149/// using a QR code.
150#[derive(Debug, Error)]
151pub enum QRCodeGrantLoginError {
152    /// Secrets backup not set up.
153    #[error("Secrets backup not set up")]
154    MissingSecretsBackup(Option<SecretsBundleExportError>),
155
156    /// The check code was incorrect.
157    #[error("The check code was incorrect")]
158    InvalidCheckCode,
159
160    /// The rendezvous session was not found and might have expired.
161    #[error("The rendezvous session was not found and might have expired")]
162    NotFound,
163
164    /// Auth handshake error.
165    #[error("Auth handshake error: {0}")]
166    Unknown(String),
167
168    /// Unsupported protocol.
169    #[error("Unsupported protocol: {0}")]
170    UnsupportedProtocol(LoginProtocolType),
171
172    /// The homeserver doesn't support any of the login protocols that we can
173    /// offer to the new device.
174    #[error("The homeserver doesn't support any of the login protocols we can offer")]
175    NoSupportedProtocols,
176
177    /// The requested device ID is already in use.
178    #[error("The requested device ID is already in use")]
179    DeviceIDAlreadyInUse,
180
181    /// The requested device was not returned by the homeserver.
182    #[error("The requested device was not returned by the homeserver")]
183    DeviceNotFound,
184
185    /// An error happened while exchanging messages with the other device.
186    #[error(transparent)]
187    SecureChannel(SecureChannelError),
188
189    /// An unexpected message was received from the other device.
190    #[error("We have received an unexpected message, expected: {expected}, got {received:?}")]
191    UnexpectedMessage {
192        /// The message we expected.
193        expected: &'static str,
194        /// The message we received instead.
195        received: Box<QrAuthMessage>,
196    },
197
198    /// The other device has signaled to us that the login has failed.
199    #[error("The login failed, reason: {reason}")]
200    LoginFailure {
201        /// The reason, as signaled by the other device, for the login failure.
202        reason: LoginFailureReason,
203    },
204}
205
206impl From<SecureChannelError> for QRCodeGrantLoginError {
207    fn from(e: SecureChannelError) -> Self {
208        match e {
209            SecureChannelError::RendezvousChannel(ref http_error) => {
210                if let Some(ErrorKind::NotFound) = http_error.client_api_error_kind() {
211                    return Self::NotFound;
212                }
213                Self::SecureChannel(e)
214            }
215            SecureChannelError::InvalidCheckCode => Self::InvalidCheckCode,
216            e => Self::SecureChannel(e),
217        }
218    }
219}
220
221impl From<SecretsBundleExportError> for QRCodeGrantLoginError {
222    fn from(e: SecretsBundleExportError) -> Self {
223        Self::MissingSecretsBackup(Some(e))
224    }
225}
226
227/// Error type which describes failures when messages which are received over
228/// the secure channel fail to be decoded.
229#[derive(Debug, Error)]
230pub enum MessageDecodeError {
231    /// A received message has failed to be decoded.
232    #[error(transparent)]
233    Ecies(#[from] EciesMessageDecodeError),
234
235    /// A received message has failed to be decoded.
236    #[error(transparent)]
237    Hpke(#[from] HpkeMessageDecodeError),
238
239    /// A message we received over the secure channel was not a valid UTF-8
240    /// encoded string.
241    #[error(transparent)]
242    Utf8(#[from] std::str::Utf8Error),
243
244    /// A message couldn't be deserialized from JSON.
245    #[error(transparent)]
246    Json(#[from] serde_json::Error),
247
248    /// The sequence token of the rendezvous channel needs to be at most
249    /// [`u8::MAX`] bytes long, otherwise it can't be encoded as additional
250    /// authenticated data.
251    #[error("The sequence token is too long")]
252    TooLongSequenceToken(InvalidLengthError),
253
254    /// The base URL of the homeserver needs to be at most [`u8::MAX`] bytes
255    /// long, otherwise it can't be encoded as additional authenticated data.
256    #[error("The base URL of the homeserver is too long")]
257    TooLongBaseUrl(InvalidLengthError),
258
259    /// The rendezvous ID of the channel needs to be at most [`u8::MAX`] bytes
260    /// long, otherwise it can't be encoded as additional authenticated data.
261    #[error("The rendezvous ID is too long")]
262    TooLongRendezvousId(InvalidLengthError),
263}
264
265/// Error type for decryption failures of the secure channel.
266#[derive(Debug, Error)]
267pub enum DecryptionError {
268    /// A ECIES message failed to be decrypted.
269    #[error(transparent)]
270    Ecies(#[from] EciesError),
271    /// A HPKE message failed to be decrypted.
272    #[error(transparent)]
273    Hpke(#[from] HpkeError),
274}
275
276/// Error type for failures in when receiving or sending messages over the
277/// secure channel.
278#[derive(Debug, Error)]
279pub enum SecureChannelError {
280    /// A message has failed to be decrypted.
281    #[error(transparent)]
282    Decryption(#[from] DecryptionError),
283
284    /// A received message has failed to be decoded.
285    #[error(transparent)]
286    MessageDecode(#[from] MessageDecodeError),
287
288    /// The secure channel failed to be established because it received an
289    /// unexpected message.
290    #[error(
291        "The secure channel setup has received an unexpected message, expected: {expected}, got {received}"
292    )]
293    SecureChannelMessage {
294        /// The secure channel message we expected.
295        expected: &'static str,
296        /// The secure channel message we received instead.
297        received: String,
298    },
299
300    /// The secure channel could not have been established, the check code was
301    /// invalid.
302    #[error("The secure channel could not have been established, the check code was invalid")]
303    InvalidCheckCode,
304
305    /// An error happened in the underlying rendezvous channel.
306    #[error("Error in the rendezvous channel: {0:?}")]
307    RendezvousChannel(#[from] HttpError),
308
309    /// Both devices have advertised the same intent in the login attempt, i.e.
310    /// both sides claim to be a new device.
311    #[error(
312        "The secure channel could not have been established, \
313         the two devices have the same login intent"
314    )]
315    InvalidIntent,
316
317    /// The secure channel could not have been established, the check code
318    /// cannot be received.
319    #[error(
320        "The secure channel could not have been established, \
321         the check code cannot be received"
322    )]
323    CannotReceiveCheckCode,
324
325    /// The QR code specifies an unsupported protocol version.
326    #[error("The QR code specifies an unsupported protocol version")]
327    UnsupportedQrCodeType,
328
329    /// The QR code couldn't have been created.
330    #[error(transparent)]
331    QrCodeCreationError(#[from] QrCodeCreationError),
332}
333
334/// Metadata to be used with [`LoginProgress::EstablishingSecureChannel`] or
335/// [`GrantLoginProgress::EstablishingSecureChannel`] when this device is the
336/// one scanning the QR code.
337///
338/// We have established the secure channel, but we need to let the other side
339/// know about the check code so they can verify that the secure channel is
340/// indeed secure.
341#[derive(Clone, Debug)]
342pub struct QrProgress {
343    /// The check code we need to, out of band, send to the other device.
344    pub check_code: u8,
345}
346
347/// Metadata to be used with [`LoginProgress::EstablishingSecureChannel`] and
348/// [`GrantLoginProgress::EstablishingSecureChannel`] when this device is the
349/// one generating the QR code.
350///
351/// We have established the secure channel, but we need to let the other device
352/// know about the [`QrCodeData`] so they can connect to the channel and let us
353/// know about the check code so we can verify that the channel is indeed
354/// secure.
355#[derive(Clone, Debug)]
356pub enum GeneratedQrProgress {
357    /// The QR code has been created and this device is waiting for the other
358    /// device to scan it.
359    QrReady(QrCodeData),
360    /// The QR code has been scanned by the other device and this device is
361    /// waiting for the user to put in the check code displayed on the other
362    /// device.
363    QrScanned(CheckCodeSender),
364}
365
366/// A oneshot sender used to send the check code back to the device that
367/// generated the QR code.
368pub type CheckCodeSender = CloneableSender<u8>;
369
370impl CheckCodeSender {
371    /// Send the check code.
372    ///
373    /// Calling this method more than once will result in an error.
374    ///
375    /// # Arguments
376    ///
377    /// * `check_code` - The check code in digits representation.
378    pub async fn send(&self, check_code: u8) -> Result<(), SenderError> {
379        self.send_impl(check_code).await
380    }
381}
382
383/// The internal message of the [`ContinuationMessageSender`] to either continue
384/// the login granting process or to cancel it.
385#[derive(Clone, Copy, Debug)]
386pub(crate) enum ContinuationMessage {
387    Confirm,
388    Cancel,
389}
390
391/// Struct used to let the QR code granting logic know that it can continue with
392/// the process since applications might suspend things while the verification
393/// URI is open.
394#[derive(Clone, Debug)]
395pub struct ContinuationMessageSender(CloneableSender<ContinuationMessage>);
396
397impl ContinuationMessageSender {
398    /// Confirm the continuation of the login granting process.
399    pub async fn confirm(&self) -> Result<(), SenderError> {
400        self.0.send_impl(ContinuationMessage::Confirm).await
401    }
402
403    /// Cancel the login granting process.
404    pub async fn cancel(&self) -> Result<(), SenderError> {
405        self.0.send_impl(ContinuationMessage::Cancel).await
406    }
407}
408
409/// A oneshot sender we are able to clone so we can put it into a
410/// [`SharedObservable`](eyeball::SharedObservable).
411#[derive(Clone, Debug)]
412pub struct CloneableSender<T> {
413    inner: Arc<Mutex<Option<tokio::sync::oneshot::Sender<T>>>>,
414}
415
416impl<T> CloneableSender<T> {
417    pub(crate) fn new(tx: tokio::sync::oneshot::Sender<T>) -> Self {
418        Self { inner: Arc::new(Mutex::new(Some(tx))) }
419    }
420
421    async fn send_impl(&self, message: T) -> Result<(), SenderError> {
422        match self.inner.lock().await.take() {
423            Some(tx) => tx.send(message).map_err(|_| SenderError::CannotSend),
424            None => Err(SenderError::AlreadySent),
425        }
426    }
427}
428
429/// Possible errors when calling [`CloneableSender::send`].
430#[derive(Debug, thiserror::Error)]
431pub enum SenderError {
432    /// The message has already been sent.
433    #[error("message already sent.")]
434    AlreadySent,
435    /// The message cannot be sent.
436    #[error("message cannot be sent.")]
437    CannotSend,
438}
439
440#[cfg(all(test, not(target_family = "wasm"), feature = "unstable-msc4388"))]
441mod tests {
442    use matrix_sdk_test::async_test;
443    use serde_json::json;
444    use wiremock::{
445        Mock, ResponseTemplate,
446        matchers::{method, path},
447    };
448
449    use crate::test_utils::mocks::MatrixMockServer;
450
451    #[async_test]
452    async fn test_msc_4388_rendezvous_server_supported() {
453        const URL: &str = "/_matrix/client/unstable/io.element.msc4388/rendezvous";
454
455        let server = MatrixMockServer::new().await;
456        let client = server.client_builder().logged_in_with_oauth().build().await;
457
458        {
459            let _discover_guard = server
460                .server()
461                .register_as_scoped(
462                    Mock::given(method("GET"))
463                        .and(path(URL))
464                        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
465                            "create_available": true,
466                        })))
467                        .expect(1),
468                )
469                .await;
470
471            let supported = client
472                .oauth()
473                .msc_4388_rendezvous_server_supported()
474                .await
475                .expect("We should be able to check if the rendezvous server is supported");
476
477            assert!(supported, "The rendezvous server should be supported");
478        }
479
480        {
481            let _discover_guard = server
482                .server()
483                .register_as_scoped(
484                    Mock::given(method("GET"))
485                        .and(path(URL))
486                        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
487                            "create_available": false,
488                        })))
489                        .expect(1),
490                )
491                .await;
492
493            let supported = client
494                .oauth()
495                .msc_4388_rendezvous_server_supported()
496                .await
497                .expect("We should be able to check if the rendezvous server is supported");
498
499            assert!(
500                !supported,
501                "The rendezvous server should not be supported, because create_available is false"
502            );
503        }
504
505        {
506            let _discover_guard = server
507                .server()
508                .register_as_scoped(
509                    Mock::given(method("GET"))
510                        .and(path(URL))
511                        .respond_with(ResponseTemplate::new(404))
512                        .expect(1),
513                )
514                .await;
515
516            let supported = client
517                .oauth()
518                .msc_4388_rendezvous_server_supported()
519                .await
520                .expect("We should be able to check if the rendezvous server is supported");
521
522            assert!(
523                !supported,
524                "The rendezvous server should not be supported if we receive a 404 response"
525            );
526        }
527
528        {
529            let _discover_guard = server
530                .server()
531                .register_as_scoped(
532                    Mock::given(method("GET"))
533                        .and(path(URL))
534                        .respond_with(ResponseTemplate::new(403))
535                        .expect(1),
536                )
537                .await;
538
539            let supported = client
540                .oauth()
541                .msc_4388_rendezvous_server_supported()
542                .await
543                .expect("We should be able to check if the rendezvous server is supported");
544
545            assert!(
546                !supported,
547                "The rendezvous server should not be supported if we receive a 403 response"
548            );
549        }
550
551        {
552            let _discover_guard = server
553                .server()
554                .register_as_scoped(
555                    Mock::given(method("GET"))
556                        .and(path(URL))
557                        .respond_with(ResponseTemplate::new(500))
558                        .expect(1),
559                )
560                .await;
561
562            client
563                .oauth()
564                .msc_4388_rendezvous_server_supported()
565                .await
566                .expect_err("We should return an error if the homeserver can't tell us if the endpoint is supported or not");
567        }
568    }
569}