matrix_sdk/authentication/oauth/qrcode/
mod.rs1use 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#[derive(Debug, Error)]
70#[cfg_attr(feature = "uniffi", derive(uniffi::Error), uniffi(flat_error))]
71pub enum QRCodeLoginError {
72 #[error(transparent)]
75 OAuth(#[from] DeviceAuthorizationOAuthError),
76
77 #[error("The login failed, reason: {reason}")]
79 LoginFailure {
80 reason: LoginFailureReason,
82 homeserver: Option<String>,
85 },
86
87 #[error("We have received an unexpected message, expected: {expected}, got {received:?}")]
89 UnexpectedMessage {
90 expected: &'static str,
92 received: Box<QrAuthMessage>,
94 },
95
96 #[error(transparent)]
98 SecureChannel(SecureChannelError),
99
100 #[error("The rendezvous session was not found and might have expired")]
102 NotFound,
103
104 #[error(transparent)]
106 CrossProcessRefreshLock(#[from] CrossProcessRefreshLockError),
107
108 #[error(transparent)]
112 UserIdDiscovery(HttpError),
113
114 #[error(transparent)]
117 SessionTokens(crate::Error),
118
119 #[error(transparent)]
121 DeviceKeyUpload(crate::Error),
122
123 #[error(transparent)]
126 SecretImport(#[from] SecretImportError),
127
128 #[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#[derive(Debug, Error)]
151pub enum QRCodeGrantLoginError {
152 #[error("Secrets backup not set up")]
154 MissingSecretsBackup(Option<SecretsBundleExportError>),
155
156 #[error("The check code was incorrect")]
158 InvalidCheckCode,
159
160 #[error("The rendezvous session was not found and might have expired")]
162 NotFound,
163
164 #[error("Auth handshake error: {0}")]
166 Unknown(String),
167
168 #[error("Unsupported protocol: {0}")]
170 UnsupportedProtocol(LoginProtocolType),
171
172 #[error("The homeserver doesn't support any of the login protocols we can offer")]
175 NoSupportedProtocols,
176
177 #[error("The requested device ID is already in use")]
179 DeviceIDAlreadyInUse,
180
181 #[error("The requested device was not returned by the homeserver")]
183 DeviceNotFound,
184
185 #[error(transparent)]
187 SecureChannel(SecureChannelError),
188
189 #[error("We have received an unexpected message, expected: {expected}, got {received:?}")]
191 UnexpectedMessage {
192 expected: &'static str,
194 received: Box<QrAuthMessage>,
196 },
197
198 #[error("The login failed, reason: {reason}")]
200 LoginFailure {
201 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#[derive(Debug, Error)]
230pub enum MessageDecodeError {
231 #[error(transparent)]
233 Ecies(#[from] EciesMessageDecodeError),
234
235 #[error(transparent)]
237 Hpke(#[from] HpkeMessageDecodeError),
238
239 #[error(transparent)]
242 Utf8(#[from] std::str::Utf8Error),
243
244 #[error(transparent)]
246 Json(#[from] serde_json::Error),
247
248 #[error("The sequence token is too long")]
252 TooLongSequenceToken(InvalidLengthError),
253
254 #[error("The base URL of the homeserver is too long")]
257 TooLongBaseUrl(InvalidLengthError),
258
259 #[error("The rendezvous ID is too long")]
262 TooLongRendezvousId(InvalidLengthError),
263}
264
265#[derive(Debug, Error)]
267pub enum DecryptionError {
268 #[error(transparent)]
270 Ecies(#[from] EciesError),
271 #[error(transparent)]
273 Hpke(#[from] HpkeError),
274}
275
276#[derive(Debug, Error)]
279pub enum SecureChannelError {
280 #[error(transparent)]
282 Decryption(#[from] DecryptionError),
283
284 #[error(transparent)]
286 MessageDecode(#[from] MessageDecodeError),
287
288 #[error(
291 "The secure channel setup has received an unexpected message, expected: {expected}, got {received}"
292 )]
293 SecureChannelMessage {
294 expected: &'static str,
296 received: String,
298 },
299
300 #[error("The secure channel could not have been established, the check code was invalid")]
303 InvalidCheckCode,
304
305 #[error("Error in the rendezvous channel: {0:?}")]
307 RendezvousChannel(#[from] HttpError),
308
309 #[error(
312 "The secure channel could not have been established, \
313 the two devices have the same login intent"
314 )]
315 InvalidIntent,
316
317 #[error(
320 "The secure channel could not have been established, \
321 the check code cannot be received"
322 )]
323 CannotReceiveCheckCode,
324
325 #[error("The QR code specifies an unsupported protocol version")]
327 UnsupportedQrCodeType,
328
329 #[error(transparent)]
331 QrCodeCreationError(#[from] QrCodeCreationError),
332}
333
334#[derive(Clone, Debug)]
342pub struct QrProgress {
343 pub check_code: u8,
345}
346
347#[derive(Clone, Debug)]
356pub enum GeneratedQrProgress {
357 QrReady(QrCodeData),
360 QrScanned(CheckCodeSender),
364}
365
366pub type CheckCodeSender = CloneableSender<u8>;
369
370impl CheckCodeSender {
371 pub async fn send(&self, check_code: u8) -> Result<(), SenderError> {
379 self.send_impl(check_code).await
380 }
381}
382
383#[derive(Clone, Copy, Debug)]
386pub(crate) enum ContinuationMessage {
387 Confirm,
388 Cancel,
389}
390
391#[derive(Clone, Debug)]
395pub struct ContinuationMessageSender(CloneableSender<ContinuationMessage>);
396
397impl ContinuationMessageSender {
398 pub async fn confirm(&self) -> Result<(), SenderError> {
400 self.0.send_impl(ContinuationMessage::Confirm).await
401 }
402
403 pub async fn cancel(&self) -> Result<(), SenderError> {
405 self.0.send_impl(ContinuationMessage::Cancel).await
406 }
407}
408
409#[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#[derive(Debug, thiserror::Error)]
431pub enum SenderError {
432 #[error("message already sent.")]
434 AlreadySent,
435 #[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}