matrix_sdk/authentication/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//! [`Oidc::login_with_qr_code()`] method.
23
24use as_variant::as_variant;
25use matrix_sdk_base::crypto::SecretImportError;
26pub use oauth2::{
27    basic::{BasicErrorResponse, BasicRequestTokenError},
28    ConfigurationError, DeviceCodeErrorResponse, DeviceCodeErrorResponseType, HttpClientError,
29    RequestTokenError, StandardErrorResponse,
30};
31use thiserror::Error;
32use url::Url;
33pub use vodozemac::ecies::{Error as EciesError, MessageDecodeError};
34
35#[cfg(doc)]
36use crate::authentication::oidc::Oidc;
37use crate::{authentication::oidc::CrossProcessRefreshLockError, HttpError};
38
39mod login;
40mod messages;
41mod oauth_client;
42mod rendezvous_channel;
43mod secure_channel;
44
45pub use matrix_sdk_base::crypto::types::qr_login::{
46    LoginQrCodeDecodeError, QrCodeData, QrCodeMode, QrCodeModeData,
47};
48
49pub use self::{
50    login::{LoginProgress, LoginWithQrCode},
51    messages::{LoginFailureReason, LoginProtocolType, QrAuthMessage},
52};
53
54/// The error type for failures while trying to log in a new device using a QR
55/// code.
56#[derive(Debug, Error)]
57#[cfg_attr(feature = "uniffi", derive(uniffi::Error), uniffi(flat_error))]
58pub enum QRCodeLoginError {
59    /// An error happened while we were communicating with the OAuth 2.0
60    /// authorization server.
61    #[error(transparent)]
62    Oauth(#[from] DeviceAuthorizationOauthError),
63
64    /// The other device has signaled to us that the login has failed.
65    #[error("The login failed, reason: {reason}")]
66    LoginFailure {
67        /// The reason, as signaled by the other device, for the login failure.
68        reason: LoginFailureReason,
69        /// The homeserver that we attempted to log in to.
70        homeserver: Option<Url>,
71    },
72
73    /// An unexpected message was received from the other device.
74    #[error("We have received an unexpected message, expected: {expected}, got {received:?}")]
75    UnexpectedMessage {
76        /// The message we expected.
77        expected: &'static str,
78        /// The message we received instead.
79        received: QrAuthMessage,
80    },
81
82    /// An error happened while exchanging messages with the other device.
83    #[error(transparent)]
84    SecureChannel(#[from] SecureChannelError),
85
86    /// The cross-process refresh lock failed to be initialized.
87    #[error(transparent)]
88    CrossProcessRefreshLock(#[from] CrossProcessRefreshLockError),
89
90    /// An error happened while we were trying to discover our user and device
91    /// ID, after we have acquired an access token from the OAuth 2.0
92    /// authorization server.
93    #[error(transparent)]
94    UserIdDiscovery(HttpError),
95
96    /// We failed to set the session tokens after we figured out our device and
97    /// user IDs.
98    #[error(transparent)]
99    SessionTokens(crate::Error),
100
101    /// The device keys failed to be uploaded after we successfully logged in.
102    #[error(transparent)]
103    DeviceKeyUpload(crate::Error),
104
105    /// The secrets bundle we received from the existing device failed to be
106    /// imported.
107    #[error(transparent)]
108    SecretImport(#[from] SecretImportError),
109}
110
111/// Error type describing failures in the interaction between the device
112/// attempting to log in and the OAuth 2.0 authorization server.
113#[derive(Debug, Error)]
114pub enum DeviceAuthorizationOauthError {
115    /// A generic OAuth 2.0 error happened while we were attempting to register
116    /// the device with the OAuth 2.0 authorization server.
117    #[error(transparent)]
118    Oauth(#[from] crate::authentication::oidc::OidcError),
119
120    /// The OAuth 2.0 server doesn't support the device authorization grant.
121    #[error("OAuth 2.0 server doesn't support the device authorization grant")]
122    NoDeviceAuthorizationEndpoint,
123
124    /// An error happened while we attempted to request a device authorization
125    /// from the Oauth 2.0 authorization server.
126    #[error(transparent)]
127    DeviceAuthorization(#[from] BasicRequestTokenError<HttpClientError<reqwest::Error>>),
128
129    /// An error happened while waiting for the access token to be issued and
130    /// sent to us by the Oauth 2.0 authorization server.
131    #[error(transparent)]
132    RequestToken(
133        #[from] RequestTokenError<HttpClientError<reqwest::Error>, DeviceCodeErrorResponse>,
134    ),
135}
136
137impl DeviceAuthorizationOauthError {
138    /// If the [`DeviceAuthorizationOauthError`] is of the
139    /// [`DeviceCodeErrorResponseType`] error variant, return it.
140    pub fn as_request_token_error(&self) -> Option<&DeviceCodeErrorResponseType> {
141        let error = as_variant!(self, DeviceAuthorizationOauthError::RequestToken)?;
142        let request_token_error = as_variant!(error, RequestTokenError::ServerResponse)?;
143
144        Some(request_token_error.error())
145    }
146}
147
148/// Error type for failures in when receiving or sending messages over the
149/// secure channel.
150#[derive(Debug, Error)]
151pub enum SecureChannelError {
152    /// A message we received over the secure channel was not a valid UTF-8
153    /// encoded string.
154    #[error(transparent)]
155    Utf8(#[from] std::str::Utf8Error),
156
157    /// A message has failed to be decrypted.
158    #[error(transparent)]
159    Ecies(#[from] EciesError),
160
161    /// A received message has failed to be decoded.
162    #[error(transparent)]
163    MessageDecode(#[from] MessageDecodeError),
164
165    /// A message couldn't be deserialized from JSON.
166    #[error(transparent)]
167    Json(#[from] serde_json::Error),
168
169    /// The secure channel failed to be established because it received an
170    /// unexpected message.
171    #[error(
172        "The secure channel setup has received an unexpected message, expected: {expected}, got {received}"
173    )]
174    SecureChannelMessage {
175        /// The secure channel message we expected.
176        expected: &'static str,
177        /// The secure channel message we received instead.
178        received: String,
179    },
180
181    /// The secure channel could not have been established, the check code was
182    /// invalid.
183    #[error("The secure channel could not have been established, the check code was invalid")]
184    InvalidCheckCode,
185
186    /// An error happened in the underlying rendezvous channel.
187    #[error("Error in the rendezvous channel: {0:?}")]
188    RendezvousChannel(#[from] HttpError),
189
190    /// Both devices have advertised the same intent in the login attempt, i.e.
191    /// both sides claim to be a new device.
192    #[error("The secure channel could not have been established, the two devices have the same login intent")]
193    InvalidIntent,
194}