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
26use as_variant::as_variant;
27pub use matrix_sdk_base::crypto::types::qr_login::{
28 LoginQrCodeDecodeError, QrCodeData, QrCodeMode, QrCodeModeData,
29};
30use matrix_sdk_base::crypto::{SecretImportError, store::SecretsBundleExportError};
31pub use oauth2::{
32 ConfigurationError, DeviceCodeErrorResponse, DeviceCodeErrorResponseType, HttpClientError,
33 RequestTokenError, StandardErrorResponse,
34 basic::{BasicErrorResponse, BasicRequestTokenError},
35};
36use ruma::api::{client::error::ErrorKind, error::FromHttpResponseError};
37use thiserror::Error;
38use tokio::sync::Mutex;
39use url::Url;
40use vodozemac::ecies::CheckCode;
41pub use vodozemac::ecies::{Error as EciesError, MessageDecodeError};
42
43mod grant;
44mod login;
45mod messages;
46mod rendezvous_channel;
47mod secure_channel;
48
49pub use self::{
50 grant::{GrantLoginProgress, GrantLoginWithGeneratedQrCode, GrantLoginWithScannedQrCode},
51 login::{LoginProgress, LoginWithGeneratedQrCode, LoginWithQrCode},
52 messages::{LoginFailureReason, LoginProtocolType, QrAuthMessage},
53};
54use super::CrossProcessRefreshLockError;
55#[cfg(doc)]
56use super::OAuth;
57use crate::HttpError;
58
59/// The error type for failures while trying to log in a new device using a QR
60/// code.
61#[derive(Debug, Error)]
62#[cfg_attr(feature = "uniffi", derive(uniffi::Error), uniffi(flat_error))]
63pub enum QRCodeLoginError {
64 /// An error happened while we were communicating with the OAuth 2.0
65 /// authorization server.
66 #[error(transparent)]
67 OAuth(#[from] DeviceAuthorizationOAuthError),
68
69 /// The other device has signaled to us that the login has failed.
70 #[error("The login failed, reason: {reason}")]
71 LoginFailure {
72 /// The reason, as signaled by the other device, for the login failure.
73 reason: LoginFailureReason,
74 /// The homeserver that we attempted to log in to.
75 homeserver: Option<Url>,
76 },
77
78 /// An unexpected message was received from the other device.
79 #[error("We have received an unexpected message, expected: {expected}, got {received:?}")]
80 UnexpectedMessage {
81 /// The message we expected.
82 expected: &'static str,
83 /// The message we received instead.
84 received: QrAuthMessage,
85 },
86
87 /// An error happened while exchanging messages with the other device.
88 #[error(transparent)]
89 SecureChannel(SecureChannelError),
90
91 /// The rendezvous session was not found and might have expired.
92 #[error("The rendezvous session was not found and might have expired")]
93 NotFound,
94
95 /// The cross-process refresh lock failed to be initialized.
96 #[error(transparent)]
97 CrossProcessRefreshLock(#[from] CrossProcessRefreshLockError),
98
99 /// An error happened while we were trying to discover our user and device
100 /// ID, after we have acquired an access token from the OAuth 2.0
101 /// authorization server.
102 #[error(transparent)]
103 UserIdDiscovery(HttpError),
104
105 /// We failed to set the session tokens after we figured out our device and
106 /// user IDs.
107 #[error(transparent)]
108 SessionTokens(crate::Error),
109
110 /// The device keys failed to be uploaded after we successfully logged in.
111 #[error(transparent)]
112 DeviceKeyUpload(crate::Error),
113
114 /// The secrets bundle we received from the existing device failed to be
115 /// imported.
116 #[error(transparent)]
117 SecretImport(#[from] SecretImportError),
118
119 /// The other party told us to use a different homeserver but we failed to
120 /// reset the server URL.
121 #[error(transparent)]
122 ServerReset(crate::Error),
123}
124
125impl From<SecureChannelError> for QRCodeLoginError {
126 fn from(e: SecureChannelError) -> Self {
127 match e {
128 SecureChannelError::RendezvousChannel(HttpError::Api(ref boxed)) => {
129 if let FromHttpResponseError::Server(api_error) = boxed.as_ref()
130 && let Some(ErrorKind::NotFound) =
131 api_error.as_client_api_error().and_then(|e| e.error_kind())
132 {
133 return Self::NotFound;
134 }
135 Self::SecureChannel(e)
136 }
137 e => Self::SecureChannel(e),
138 }
139 }
140}
141
142/// The error type for failures while trying to grant log in to a new device
143/// using a QR code.
144#[derive(Debug, Error)]
145pub enum QRCodeGrantLoginError {
146 /// Secrets backup not set up.
147 #[error("Secrets backup not set up")]
148 MissingSecretsBackup(Option<SecretsBundleExportError>),
149
150 /// The check code was incorrect.
151 #[error("The check code was incorrect")]
152 InvalidCheckCode,
153
154 /// The device could not be created.
155 #[error("The device could not be created")]
156 UnableToCreateDevice,
157
158 /// The rendezvous session was not found and might have expired.
159 #[error("The rendezvous session was not found and might have expired")]
160 NotFound,
161
162 /// Auth handshake error.
163 #[error("Auth handshake error: {0}")]
164 Unknown(String),
165
166 /// Unsupported protocol.
167 #[error("Unsupported protocol: {0}")]
168 UnsupportedProtocol(LoginProtocolType),
169
170 /// The requested device ID is already in use.
171 #[error("The requested device ID is already in use")]
172 DeviceIDAlreadyInUse,
173}
174
175impl From<SecureChannelError> for QRCodeGrantLoginError {
176 fn from(e: SecureChannelError) -> Self {
177 match e {
178 SecureChannelError::RendezvousChannel(HttpError::Api(ref boxed)) => {
179 if let FromHttpResponseError::Server(api_error) = boxed.as_ref()
180 && let Some(ErrorKind::NotFound) =
181 api_error.as_client_api_error().and_then(|e| e.error_kind())
182 {
183 return Self::NotFound;
184 }
185 Self::Unknown(e.to_string())
186 }
187 SecureChannelError::InvalidCheckCode => Self::InvalidCheckCode,
188 e => Self::Unknown(e.to_string()),
189 }
190 }
191}
192
193impl From<SecretsBundleExportError> for QRCodeGrantLoginError {
194 fn from(e: SecretsBundleExportError) -> Self {
195 Self::MissingSecretsBackup(Some(e))
196 }
197}
198
199/// Error type describing failures in the interaction between the device
200/// attempting to log in and the OAuth 2.0 authorization server.
201#[derive(Debug, Error)]
202pub enum DeviceAuthorizationOAuthError {
203 /// A generic OAuth 2.0 error happened while we were attempting to register
204 /// the device with the OAuth 2.0 authorization server.
205 #[error(transparent)]
206 OAuth(#[from] crate::authentication::oauth::OAuthError),
207
208 /// The OAuth 2.0 server doesn't support the device authorization grant.
209 #[error("OAuth 2.0 server doesn't support the device authorization grant")]
210 NoDeviceAuthorizationEndpoint,
211
212 /// An error happened while we attempted to request a device authorization
213 /// from the OAuth 2.0 authorization server.
214 #[error(transparent)]
215 DeviceAuthorization(#[from] BasicRequestTokenError<HttpClientError<reqwest::Error>>),
216
217 /// An error happened while waiting for the access token to be issued and
218 /// sent to us by the OAuth 2.0 authorization server.
219 #[error(transparent)]
220 RequestToken(
221 #[from] RequestTokenError<HttpClientError<reqwest::Error>, DeviceCodeErrorResponse>,
222 ),
223}
224
225impl DeviceAuthorizationOAuthError {
226 /// If the [`DeviceAuthorizationOAuthError`] is of the
227 /// [`DeviceCodeErrorResponseType`] error variant, return it.
228 pub fn as_request_token_error(&self) -> Option<&DeviceCodeErrorResponseType> {
229 let error = as_variant!(self, DeviceAuthorizationOAuthError::RequestToken)?;
230 let request_token_error = as_variant!(error, RequestTokenError::ServerResponse)?;
231
232 Some(request_token_error.error())
233 }
234}
235
236/// Error type for failures in when receiving or sending messages over the
237/// secure channel.
238#[derive(Debug, Error)]
239pub enum SecureChannelError {
240 /// A message we received over the secure channel was not a valid UTF-8
241 /// encoded string.
242 #[error(transparent)]
243 Utf8(#[from] std::str::Utf8Error),
244
245 /// A message has failed to be decrypted.
246 #[error(transparent)]
247 Ecies(#[from] EciesError),
248
249 /// A received message has failed to be decoded.
250 #[error(transparent)]
251 MessageDecode(#[from] MessageDecodeError),
252
253 /// A message couldn't be deserialized from JSON.
254 #[error(transparent)]
255 Json(#[from] serde_json::Error),
256
257 /// The secure channel failed to be established because it received an
258 /// unexpected message.
259 #[error(
260 "The secure channel setup has received an unexpected message, expected: {expected}, got {received}"
261 )]
262 SecureChannelMessage {
263 /// The secure channel message we expected.
264 expected: &'static str,
265 /// The secure channel message we received instead.
266 received: String,
267 },
268
269 /// The secure channel could not have been established, the check code was
270 /// invalid.
271 #[error("The secure channel could not have been established, the check code was invalid")]
272 InvalidCheckCode,
273
274 /// An error happened in the underlying rendezvous channel.
275 #[error("Error in the rendezvous channel: {0:?}")]
276 RendezvousChannel(#[from] HttpError),
277
278 /// Both devices have advertised the same intent in the login attempt, i.e.
279 /// both sides claim to be a new device.
280 #[error(
281 "The secure channel could not have been established, \
282 the two devices have the same login intent"
283 )]
284 InvalidIntent,
285
286 /// The secure channel could not have been established, the check code
287 /// cannot be received.
288 #[error(
289 "The secure channel could not have been established, \
290 the check code cannot be received"
291 )]
292 CannotReceiveCheckCode,
293}
294
295/// Metadata to be used with [`LoginProgress::EstablishingSecureChannel`]
296/// or [`GrantLoginProgress::EstablishingSecureChannel`] when
297/// this device is the one scanning the QR code.
298///
299/// We have established the secure channel, but we need to let the other
300/// side know about the [`CheckCode`] so they can verify that the secure
301/// channel is indeed secure.
302#[derive(Clone, Debug)]
303pub struct QrProgress {
304 /// The check code we need to, out of band, send to the other device.
305 pub check_code: CheckCode,
306}
307
308/// Metadata to be used with [`LoginProgress::EstablishingSecureChannel`] and
309/// [`GrantLoginProgress::EstablishingSecureChannel`] when this device is the
310/// one generating the QR code.
311///
312/// We have established the secure channel, but we need to let the
313/// other device know about the [`QrCodeData`] so they can connect to the
314/// channel and let us know about the checkcode so we can verify that the
315/// channel is indeed secure.
316#[derive(Clone, Debug)]
317pub enum GeneratedQrProgress {
318 /// The QR code has been created and this device is waiting for the other
319 /// device to scan it.
320 QrReady(QrCodeData),
321 /// The QR code has been scanned by the other device and this device is
322 /// waiting for the user to put in the checkcode displayed on the
323 /// other device.
324 QrScanned(CheckCodeSender),
325}
326
327/// Used to pass back the checkcode entered by the user to verify that the
328/// secure channel is indeed secure.
329#[derive(Clone, Debug)]
330pub struct CheckCodeSender {
331 inner: Arc<Mutex<Option<tokio::sync::oneshot::Sender<u8>>>>,
332}
333
334impl CheckCodeSender {
335 pub(crate) fn new(tx: tokio::sync::oneshot::Sender<u8>) -> Self {
336 Self { inner: Arc::new(Mutex::new(Some(tx))) }
337 }
338
339 /// Send the checkcode.
340 ///
341 /// Calling this method more than once will result in an error.
342 ///
343 /// # Arguments
344 ///
345 /// * `check_code` - The check code in digits representation.
346 pub async fn send(&self, check_code: u8) -> Result<(), CheckCodeSenderError> {
347 match self.inner.lock().await.take() {
348 Some(tx) => tx.send(check_code).map_err(|_| CheckCodeSenderError::CannotSend),
349 None => Err(CheckCodeSenderError::AlreadySent),
350 }
351 }
352}
353
354/// Possible errors when calling [`CheckCodeSender::send`].
355#[derive(Debug, thiserror::Error)]
356pub enum CheckCodeSenderError {
357 /// The check code has already been sent.
358 #[error("check code already sent.")]
359 AlreadySent,
360 /// The check code cannot be sent.
361 #[error("check code cannot be sent.")]
362 CannotSend,
363}