matrix_sdk/authentication/oauth/mod.rs
1// Copyright 2022 Kévin Commaille
2// Copyright 2026 Nordeck IT + Consulting GmbH <info@nordeck.net>
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! High-level OAuth 2.0 API.
17//!
18//! The OAuth 2.0 interactions with the Matrix API are currently a
19//! work-in-progress and are defined by [MSC3861] and its sub-proposals. And
20//! more documentation is available at [areweoidcyet.com].
21//!
22//! This authentication API is available with [`Client::oauth()`].
23//!
24//! # Homeserver support
25//!
26//! After building the client, you can check that the homeserver supports
27//! logging in via OAuth 2.0 when [`OAuth::server_metadata()`] succeeds.
28//!
29//! # Registration
30//!
31//! Clients must register with the homeserver before being able to interact with
32//! an OAuth 2.0 server.
33//!
34//! The registration consists in providing client metadata to the authorization
35//! server, to declare the interactions that the client supports with the
36//! homeserver. This step is important because the client cannot use a feature
37//! that is not declared during registration. In return, the server assigns an
38//! ID and eventually credentials to the client, which will allow to identify
39//! the client when authorization requests are made.
40//!
41//! Note that only public clients are supported by this API, i.e. clients
42//! without credentials.
43//!
44//! The registration step can be done automatically by providing a
45//! [`ClientRegistrationData`] to the login method.
46//!
47//! If the server supports dynamic registration, registration can be performed
48//! manually by using [`OAuth::register_client()`]. If dynamic registration is
49//! not available, the homeserver should document how to obtain a client ID. The
50//! client ID can then be provided with [`OAuth::restore_registered_client()`].
51//!
52//! # Login
53//!
54//! Currently, three login methods are supported by this API.
55//!
56//! ## Login with the Authorization Code flow
57//!
58//! The use of the Authorization Code flow is defined in [MSC2964] and [RFC
59//! 6749][rfc6749-auth-code].
60//!
61//! This method requires to open a URL in the end-user's browser where
62//! they will be able to log into their account in the server's web UI and grant
63//! access to their Matrix account.
64//!
65//! [`OAuth::login()`] constructs an [`OAuthAuthCodeUrlBuilder`] that can be
66//! configured, and then calling [`OAuthAuthCodeUrlBuilder::build()`] will
67//! provide the URL to present to the user in a web browser.
68//!
69//! After authenticating with the server, the user will be redirected to the
70//! provided redirect URI, with a code in the query that will allow to finish
71//! the login process by calling [`OAuth::finish_login()`].
72//!
73//! If the login needs to be cancelled before its completion,
74//! [`OAuth::abort_login()`] should be called to clean up the local data.
75//!
76//! ## Login with the Device Authorization Grant
77//!
78//! The Device Authorization Grant is defined in [RFC 8628], and its use in
79//! Matrix is specified in the [Matrix specification].
80//!
81//! This method is meant for clients that cannot open a browser or have limited
82//! input capabilities, like bots, bridges or command-line applications. The
83//! end-user needs to open a verification URI on another device, where they
84//! will be able to log into their account in the server's web UI and grant
85//! access to their Matrix account.
86//!
87//! The login happens in two steps. [`OAuth::login_with_device_code()`]
88//! requests the authorization and returns a [`DeviceCodeLogin`], with the
89//! verification URI and the user code to present to the end-user. Then
90//! [`DeviceCodeLogin::finish()`] waits for the end-user to grant the
91//! authorization and completes the login.
92//!
93//! ## Login by scanning a QR Code
94//!
95//! Logging in via a QR code is defined in [MSC4108]. It uses the Device
96//! authorization flow specified in [RFC 8628].
97//!
98//! This method requires to have another logged-in Matrix device that can
99//! display a QR Code.
100//!
101//! This login method is only available if the `e2e-encryption` cargo feature is
102//! enabled. It is not available on WASM.
103//!
104//! After scanning the QR Code, [`OAuth::login_with_qr_code()`] can be called
105//! with the QR Code's data. Then the different steps of the process need to be
106//! followed with [`LoginWithQrCode::subscribe_to_progress()`].
107//!
108//! A successful login using this method will automatically mark the device as
109//! verified and transfer all end-to-end encryption related secrets, like the
110//! private cross-signing keys and the backup key from the existing device to
111//! the new device.
112//!
113//! # Persisting/restoring a session
114//!
115//! The full session to persist can be obtained with [`OAuth::full_session()`].
116//! The different parts can also be retrieved with [`Client::session_meta()`],
117//! [`Client::session_tokens()`] and [`OAuth::client_id()`].
118//!
119//! To restore a previous session, use [`OAuth::restore_session()`].
120//!
121//! # Refresh tokens
122//!
123//! The use of refresh tokens with OAuth 2.0 servers is more common than in the
124//! Matrix specification. For this reason, it is recommended to configure the
125//! client with [`ClientBuilder::handle_refresh_tokens()`], to handle refreshing
126//! tokens automatically.
127//!
128//! Applications should then listen to session tokens changes after logging in
129//! with [`Client::subscribe_to_session_changes()`] to persist them on every
130//! change. If they are not persisted properly, the end-user will need to login
131//! again.
132//!
133//! # Unknown token error
134//!
135//! A request to the Matrix API can return an [`Error`] with an
136//! [`ErrorKind::UnknownToken`].
137//!
138//! The first step is to try to refresh the token with
139//! [`OAuth::refresh_access_token()`]. This step is done automatically if the
140//! client was built with [`ClientBuilder::handle_refresh_tokens()`].
141//!
142//! If refreshing the access token fails, the next step is to try to request a
143//! new login authorization with [`OAuth::login()`], using the device ID from
144//! the session.
145//!
146//! If this fails again, the client should assume to be logged out, and all
147//! local data should be erased.
148//!
149//! # Account management.
150//!
151//! The server might advertise a URL that allows the user to manage their
152//! account. It can be used to replace most of the Matrix APIs requiring
153//! User-Interactive Authentication.
154//!
155//! The account management URL is available as `account_management_uri` on
156//! [`AuthorizationServerMetadata`]. To build a full account management URL that
157//! includes the action that the user wants to perform, use
158//! [`AuthorizationServerMetadata::account_management_url_with_action()`].
159//!
160//! # Logout
161//!
162//! To log the [`Client`] out of the session, simply call [`OAuth::logout()`].
163//!
164//! # Examples
165//!
166//! Most methods have examples, there is also an example CLI application that
167//! supports all the actions described here, in [`examples/oauth_cli`].
168//!
169//! [MSC3861]: https://github.com/matrix-org/matrix-spec-proposals/pull/3861
170//! [areweoidcyet.com]: https://areweoidcyet.com/
171//! [MSC2964]: https://github.com/matrix-org/matrix-spec-proposals/pull/2964
172//! [rfc6749-auth-code]: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1
173//! [MSC4108]: https://github.com/matrix-org/matrix-spec-proposals/pull/4108
174//! [RFC 8628]: https://datatracker.ietf.org/doc/html/rfc8628
175//! [Matrix specification]: https://spec.matrix.org/v1.19/client-server-api/#device-authorisation-flow
176//! [`ClientBuilder::handle_refresh_tokens()`]: crate::ClientBuilder::handle_refresh_tokens()
177//! [`Error`]: ruma::api::error::Error
178//! [`ErrorKind::UnknownToken`]: ruma::api::error::ErrorKind::UnknownToken
179//! [`examples/oauth_cli`]: https://github.com/matrix-org/matrix-rust-sdk/tree/main/examples/oauth_cli
180
181#[cfg(feature = "e2e-encryption")]
182use std::sync::OnceLock;
183#[cfg(feature = "e2e-encryption")]
184use std::time::Duration;
185use std::{borrow::Cow, collections::HashMap, fmt, sync::Arc};
186
187use as_variant::as_variant;
188#[cfg(feature = "e2e-encryption")]
189use error::CrossProcessRefreshLockError;
190use error::{
191 DeviceAuthorizationOAuthError, OAuthAuthorizationCodeError, OAuthClientRegistrationError,
192 OAuthDiscoveryError, OAuthTokenRevocationError, RedirectUriQueryParseError,
193};
194#[cfg(feature = "e2e-encryption")]
195use matrix_sdk_base::crypto::types::qr_login::QrCodeData;
196use matrix_sdk_base::{SessionMeta, store::RoomLoadSettings, ttl::TtlValue};
197#[cfg(feature = "e2e-encryption")]
198use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig;
199use oauth2::{
200 AccessToken, PkceCodeVerifier, RedirectUrl, RefreshToken, RevocationUrl, Scope,
201 StandardErrorResponse, StandardRevocableToken, TokenResponse, TokenUrl,
202 basic::BasicClient as OAuthClient,
203};
204pub use oauth2::{ClientId, CsrfToken};
205use oauth2_reqwest::ReqwestClient;
206use ruma::{
207 DeviceId, OwnedDeviceId,
208 api::client::discovery::get_authorization_server_metadata::{
209 self, v1::AuthorizationServerMetadata,
210 },
211 serde::Raw,
212};
213use serde::{Deserialize, Serialize};
214use sha2::Digest as _;
215use tokio::sync::Mutex;
216use tracing::{debug, error, instrument, trace, warn};
217use url::Url;
218
219mod auth_code_builder;
220#[cfg(feature = "e2e-encryption")]
221mod cross_process;
222mod device_code;
223pub mod error;
224mod http_client;
225#[cfg(feature = "e2e-encryption")]
226pub mod qrcode;
227pub mod registration;
228#[cfg(all(test, not(target_family = "wasm")))]
229mod tests;
230
231#[cfg(feature = "e2e-encryption")]
232use self::cross_process::{CrossProcessRefreshLockGuard, CrossProcessRefreshManager};
233#[cfg(feature = "e2e-encryption")]
234use self::qrcode::{
235 GrantLoginWithGeneratedQrCode, GrantLoginWithScannedQrCode, LoginWithGeneratedQrCode,
236 LoginWithQrCode,
237};
238pub use self::{
239 auth_code_builder::{OAuthAuthCodeUrlBuilder, OAuthAuthorizationData},
240 device_code::DeviceCodeLogin,
241 error::{DeviceCodeLoginError, OAuthError},
242};
243use self::{
244 http_client::OAuthHttpClient,
245 registration::{ClientMetadata, ClientRegistrationResponse, register_client},
246};
247use super::{AuthData, SessionTokens};
248use crate::{
249 Client, RefreshTokenError, Result,
250 client::{SessionChange, caches::CachedValue},
251 executor::spawn,
252 utils::UrlOrQuery,
253};
254
255pub(crate) struct OAuthCtx {
256 /// Lock and state when multiple processes may refresh an OAuth 2.0 session.
257 #[cfg(feature = "e2e-encryption")]
258 cross_process_token_refresh_manager: OnceLock<CrossProcessRefreshManager>,
259
260 /// Deferred cross-process lock initializer.
261 ///
262 /// Note: only required because we're using the crypto store that might not
263 /// be present before reloading a session.
264 #[cfg(feature = "e2e-encryption")]
265 deferred_cross_process_lock_init: Mutex<Option<String>>,
266
267 /// Whether to allow HTTP issuer URLs.
268 insecure_discover: bool,
269}
270
271impl OAuthCtx {
272 pub(crate) fn new(insecure_discover: bool) -> Self {
273 Self {
274 insecure_discover,
275 #[cfg(feature = "e2e-encryption")]
276 cross_process_token_refresh_manager: Default::default(),
277 #[cfg(feature = "e2e-encryption")]
278 deferred_cross_process_lock_init: Default::default(),
279 }
280 }
281}
282
283pub(crate) struct OAuthAuthData {
284 pub(crate) client_id: ClientId,
285 /// The data necessary to validate authorization responses.
286 authorization_data: Mutex<HashMap<CsrfToken, AuthorizationValidationData>>,
287}
288
289#[cfg(not(tarpaulin_include))]
290impl fmt::Debug for OAuthAuthData {
291 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292 f.debug_struct("OAuthAuthData").finish_non_exhaustive()
293 }
294}
295
296/// A high-level authentication API to interact with an OAuth 2.0 authorization
297/// server.
298#[derive(Debug, Clone)]
299pub struct OAuth {
300 /// The underlying Matrix API client.
301 client: Client,
302 /// The HTTP client used for making OAuth 2.0 request.
303 http_client: OAuthHttpClient,
304}
305
306impl OAuth {
307 pub(crate) fn new(client: Client) -> Self {
308 let http_client = OAuthHttpClient {
309 inner: ReqwestClient::from(client.inner.http_client.inner.clone()),
310 #[cfg(test)]
311 insecure_rewrite_https_to_http: false,
312 };
313 Self { client, http_client }
314 }
315
316 /// Rewrite HTTPS requests to use HTTP instead.
317 ///
318 /// This is a workaround to bypass some checks that require an HTTPS URL,
319 /// but we can only mock HTTP URLs.
320 #[cfg(test)]
321 pub(crate) fn insecure_rewrite_https_to_http(mut self) -> Self {
322 self.http_client.insecure_rewrite_https_to_http = true;
323 self
324 }
325
326 fn ctx(&self) -> &OAuthCtx {
327 &self.client.auth_ctx().oauth
328 }
329
330 fn http_client(&self) -> &OAuthHttpClient {
331 &self.http_client
332 }
333
334 /// Enable a cross-process store lock on the state store, to coordinate
335 /// refreshes across different processes.
336 #[cfg(feature = "e2e-encryption")]
337 pub async fn enable_cross_process_refresh_lock(
338 &self,
339 lock_value: String,
340 ) -> Result<(), OAuthError> {
341 // FIXME: it must be deferred only because we're using the crypto store
342 // and it's initialized only in `set_or_reload_session`, not if we use a
343 // dedicated store.
344 let mut lock = self.ctx().deferred_cross_process_lock_init.lock().await;
345 if lock.is_some() {
346 return Err(CrossProcessRefreshLockError::DuplicatedLock.into());
347 }
348 *lock = Some(lock_value);
349
350 Ok(())
351 }
352
353 /// Performs a deferred cross-process refresh-lock, if needs be, after an
354 /// olm machine has been initialized.
355 ///
356 /// Must be called after [`BaseClient::set_or_reload_session`].
357 #[cfg(feature = "e2e-encryption")]
358 async fn deferred_enable_cross_process_refresh_lock(&self) {
359 let deferred_init_lock = self.ctx().deferred_cross_process_lock_init.lock().await;
360
361 // Don't `take()` the value, so that subsequent calls to
362 // `enable_cross_process_refresh_lock` will keep on failing if we've
363 // enabled the lock at least once.
364 let Some(lock_value) = deferred_init_lock.as_ref() else {
365 return;
366 };
367
368 // FIXME: We shouldn't be using the crypto store for that! see also https://github.com/matrix-org/matrix-rust-sdk/issues/2472
369 let olm_machine_lock = self.client.olm_machine().await;
370 let olm_machine =
371 olm_machine_lock.as_ref().expect("there has to be an olm machine, hopefully?");
372 let store = olm_machine.store();
373 let lock = store.create_store_lock(
374 "oidc_session_refresh_lock".to_owned(),
375 CrossProcessLockConfig::multi_process(lock_value.to_owned()),
376 );
377
378 let manager = CrossProcessRefreshManager::new(store.clone(), lock);
379
380 // This method is guarded with the `deferred_cross_process_lock_init`
381 // lock held, so this `set` can't be an error.
382 let _ = self.ctx().cross_process_token_refresh_manager.set(manager);
383 }
384
385 /// The OAuth 2.0 authentication data.
386 ///
387 /// Returns `None` if the client was not registered or if the registration
388 /// was not restored with [`OAuth::restore_registered_client()`] or
389 /// [`OAuth::restore_session()`].
390 fn data(&self) -> Option<&OAuthAuthData> {
391 let data = self.client.auth_ctx().auth_data.get()?;
392 as_variant!(data, AuthData::OAuth)
393 }
394
395 /// Check if the homeserver supports the [MSC4388] variant of the rendezvous
396 /// server.
397 ///
398 /// Returns `Ok(true)` if the rendezvous discovery endpoint returns a 200 OK
399 /// HTTP response, `Ok(false)` if the endpoint returns a 404 NOT_FOUND or
400 /// 403 FORBIDDEN HTTP response, otherwise an error is returned.
401 ///
402 /// [MSC4388]: https://github.com/matrix-org/matrix-spec-proposals/pull/4388
403 #[cfg(feature = "unstable-msc4388")]
404 pub async fn msc_4388_rendezvous_server_supported(&self) -> Result<bool, crate::HttpError> {
405 use http::StatusCode;
406 use ruma::api::client::rendezvous::discover_rendezvous;
407
408 match self.client.send(discover_rendezvous::msc4388::Request::new()).await {
409 Ok(response) => Ok(response.create_available),
410 Err(e) => {
411 if e.as_client_api_error().is_some_and(|err| {
412 matches!(err.status_code, StatusCode::NOT_FOUND | StatusCode::FORBIDDEN)
413 }) {
414 Ok(false)
415 } else {
416 Err(e)
417 }
418 }
419 }
420 }
421
422 /// Log in this device using a QR code.
423 ///
424 /// # Arguments
425 ///
426 /// - `registration_data` - The data to restore or register the client with
427 /// the server. If this is not provided, an error will occur unless
428 /// [`OAuth::register_client()`] or [`OAuth::restore_registered_client()`]
429 /// was called previously.
430 #[cfg(feature = "e2e-encryption")]
431 pub fn login_with_qr_code<'a>(
432 &'a self,
433 registration_data: Option<&'a ClientRegistrationData>,
434 ) -> LoginWithQrCodeBuilder<'a> {
435 LoginWithQrCodeBuilder::new(&self.client, registration_data)
436 }
437
438 /// Grant login to a new device using a QR code.
439 #[cfg(feature = "e2e-encryption")]
440 pub fn grant_login_with_qr_code<'a>(&'a self) -> GrantLoginWithQrCodeBuilder<'a> {
441 GrantLoginWithQrCodeBuilder::new(&self.client)
442 }
443
444 /// Restore or register the OAuth 2.0 client for the server with the given
445 /// metadata, with the given optional [`ClientRegistrationData`].
446 ///
447 /// If we already have a client ID, this is a noop.
448 ///
449 /// Returns an error if there was a problem using the registration method.
450 async fn use_registration_data(
451 &self,
452 server_metadata: &AuthorizationServerMetadata,
453 data: Option<&ClientRegistrationData>,
454 ) -> std::result::Result<(), OAuthError> {
455 if self.client_id().is_some() {
456 tracing::info!("OAuth 2.0 is already configured.");
457 return Ok(());
458 }
459
460 let Some(data) = data else {
461 return Err(OAuthError::NotRegistered);
462 };
463
464 if let Some(static_registrations) = &data.static_registrations {
465 let client_id = static_registrations
466 .get(&self.client.homeserver())
467 .or_else(|| static_registrations.get(&server_metadata.issuer));
468
469 if let Some(client_id) = client_id {
470 self.restore_registered_client(client_id.clone());
471 return Ok(());
472 }
473 }
474
475 self.register_client_inner(server_metadata, &data.metadata).await?;
476
477 Ok(())
478 }
479
480 /// Get the cached OAuth 2.0 authorization server metadata of the
481 /// homeserver.
482 ///
483 /// This method will cache the metadata for a while. If the cache is not
484 /// populated it will request the server metadata, like a call to
485 /// [`OAuth::server_metadata()`], and cache the response before returning
486 /// it.
487 ///
488 /// The cache can be forced to be refreshed by calling
489 /// [`OAuth::server_metadata()`] instead.
490 ///
491 /// In most cases during the authentication process, it is better to always
492 /// fetch the metadata from the server. This is provided for convenience for
493 /// cases where the client doesn't want to incur the extra time necessary to
494 /// make the request.
495 ///
496 /// Returns an error if a problem occurred when fetching or validating the
497 /// metadata.
498 pub async fn cached_server_metadata(
499 &self,
500 ) -> Result<AuthorizationServerMetadata, OAuthDiscoveryError> {
501 let server_metadata_cache = &self.client.inner.caches.server_metadata;
502
503 if let CachedValue::Cached(metadata) = server_metadata_cache.value() {
504 if metadata.has_expired() {
505 debug!("spawning task to refresh OAuth 2.0 server metadata cache");
506
507 let oauth = self.clone();
508 self.client.task_monitor().spawn_finite_task(
509 "refresh OAuth 2.0 server metadata cache",
510 async move {
511 if let Err(error) = oauth.server_metadata().await {
512 warn!("failed to refresh OAuth 2.0 server metadata cache: {error}");
513 }
514 },
515 );
516 }
517
518 return Ok(metadata.into_data());
519 }
520
521 self.server_metadata().await
522 }
523
524 /// Fetch the OAuth 2.0 authorization server metadata of the homeserver.
525 ///
526 /// This will always request the latest server metadata from the homeserver.
527 ///
528 /// To avoid making a request each time, you can use
529 /// [`OAuth::cached_server_metadata()`].
530 ///
531 /// Returns an error if a problem occurred when fetching or validating the
532 /// metadata.
533 pub async fn server_metadata(
534 &self,
535 ) -> Result<AuthorizationServerMetadata, OAuthDiscoveryError> {
536 let server_metadata_cache = &self.client.inner.caches.server_metadata;
537
538 let mut server_metadata_guard = match server_metadata_cache.refresh_lock.try_lock() {
539 Ok(guard) => guard,
540 Err(_) => {
541 // There is already a refresh in progress, wait for it to
542 // finish.
543 let guard = server_metadata_cache.refresh_lock.lock().await;
544
545 // Reuse the data if the request was successful.
546 if matches!(*guard, Ok(()))
547 && let CachedValue::Cached(value) = server_metadata_cache.value()
548 {
549 return Ok(value.into_data());
550 }
551
552 // The previous request failed, make another request.
553 guard
554 }
555 };
556
557 match self.server_metadata_inner().await {
558 Ok(metadata) => {
559 // Always refresh the cache.
560 self.client.inner.caches.server_metadata.set_value(TtlValue::new(metadata.clone()));
561 *server_metadata_guard = Ok(());
562 Ok(metadata)
563 }
564 Err(error) => {
565 *server_metadata_guard = Err(());
566 Err(error)
567 }
568 }
569 }
570
571 async fn server_metadata_inner(
572 &self,
573 ) -> Result<AuthorizationServerMetadata, OAuthDiscoveryError> {
574 let response =
575 self.client.send(get_authorization_server_metadata::v1::Request::new()).await.map_err(
576 |error| {
577 // If the server doesn't support the endpoint.
578 if error.is_endpoint_not_implemented() {
579 OAuthDiscoveryError::NotSupported
580 } else {
581 error.into()
582 }
583 },
584 )?;
585
586 let metadata = response.metadata.deserialize()?;
587
588 if self.ctx().insecure_discover {
589 metadata.insecure_validate_urls()?;
590 } else {
591 metadata.validate_urls()?;
592 }
593
594 Ok(metadata)
595 }
596
597 /// The OAuth 2.0 unique identifier of this client obtained after
598 /// registration.
599 ///
600 /// Returns `None` if the client was not registered or if the registration
601 /// was not restored with [`OAuth::restore_registered_client()`] or
602 /// [`OAuth::restore_session()`].
603 pub fn client_id(&self) -> Option<&ClientId> {
604 self.data().map(|data| &data.client_id)
605 }
606
607 /// The OAuth 2.0 user session of this client.
608 ///
609 /// Returns `None` if the client was not logged in.
610 pub fn user_session(&self) -> Option<UserSession> {
611 let meta = self.client.session_meta()?.to_owned();
612 let tokens = self.client.session_tokens()?;
613 Some(UserSession { meta, tokens })
614 }
615
616 /// The full OAuth 2.0 session of this client.
617 ///
618 /// Returns `None` if the client was not logged in with the OAuth 2.0 API.
619 pub fn full_session(&self) -> Option<OAuthSession> {
620 let user = self.user_session()?;
621 let data = self.data()?;
622 Some(OAuthSession { client_id: data.client_id.clone(), user })
623 }
624
625 /// Register a client with the OAuth 2.0 server.
626 ///
627 /// This should be called before any authorization request with an
628 /// authorization server that supports dynamic client registration. If the
629 /// client registered with the server manually, it should use
630 /// [`OAuth::restore_registered_client()`].
631 ///
632 /// Note that this method only supports public clients, i.e. clients without
633 /// a secret.
634 ///
635 /// # Arguments
636 ///
637 /// - `client_metadata` - The serialized client metadata to register.
638 ///
639 /// # Panic
640 ///
641 /// Panics if the authentication data was already set.
642 ///
643 /// # Example
644 ///
645 /// ```no_run
646 /// use matrix_sdk::{Client, ServerName};
647 /// # use matrix_sdk::authentication::oauth::ClientId;
648 /// # use matrix_sdk::authentication::oauth::registration::ClientMetadata;
649 /// # use ruma::serde::Raw;
650 /// # let client_metadata = unimplemented!();
651 /// # fn persist_client_registration (_: url::Url, _: &ClientId) {}
652 /// # _ = async {
653 /// let server_name = ServerName::parse("myhomeserver.org")?;
654 /// let client = Client::builder().server_name(&server_name).build().await?;
655 /// let oauth = client.oauth();
656 ///
657 /// if let Err(error) = oauth.server_metadata().await {
658 /// if error.is_not_supported() {
659 /// println!("OAuth 2.0 is not supported");
660 /// }
661 ///
662 /// return Err(error.into());
663 /// }
664 ///
665 /// let response = oauth
666 /// .register_client(&client_metadata)
667 /// .await?;
668 ///
669 /// println!(
670 /// "Registered with client_id: {}",
671 /// response.client_id.as_str()
672 /// );
673 ///
674 /// // The API only supports clients without secrets.
675 /// let client_id = response.client_id;
676 ///
677 /// persist_client_registration(client.homeserver(), &client_id);
678 /// # anyhow::Ok(()) };
679 /// ```
680 pub async fn register_client(
681 &self,
682 client_metadata: &Raw<ClientMetadata>,
683 ) -> Result<ClientRegistrationResponse, OAuthError> {
684 let server_metadata = self.server_metadata().await?;
685 Ok(self.register_client_inner(&server_metadata, client_metadata).await?)
686 }
687
688 async fn register_client_inner(
689 &self,
690 server_metadata: &AuthorizationServerMetadata,
691 client_metadata: &Raw<ClientMetadata>,
692 ) -> Result<ClientRegistrationResponse, OAuthClientRegistrationError> {
693 let registration_endpoint = server_metadata
694 .registration_endpoint
695 .as_ref()
696 .ok_or(OAuthClientRegistrationError::NotSupported)?;
697
698 let registration_response =
699 register_client(self.http_client(), registration_endpoint, client_metadata).await?;
700
701 // The format of the credentials changes according to the client
702 // metadata that was sent. Public clients only get a client ID.
703 self.restore_registered_client(registration_response.client_id.clone());
704
705 Ok(registration_response)
706 }
707
708 /// Set the data of a client that is registered with an OAuth 2.0
709 /// authorization server.
710 ///
711 /// This should be called when logging in with a server that is already
712 /// known by the client.
713 ///
714 /// Note that this method only supports public clients, i.e. clients with no
715 /// credentials.
716 ///
717 /// # Arguments
718 ///
719 /// - `client_id` - The unique identifier to authenticate the client with
720 /// the server, obtained after registration.
721 ///
722 /// # Panic
723 ///
724 /// Panics if authentication data was already set.
725 pub fn restore_registered_client(&self, client_id: ClientId) {
726 let data = OAuthAuthData { client_id, authorization_data: Default::default() };
727
728 self.client
729 .auth_ctx()
730 .auth_data
731 .set(AuthData::OAuth(data))
732 .expect("Client authentication data was already set");
733 }
734
735 /// Restore a previously logged in session.
736 ///
737 /// This can be used to restore the client to a logged in state, including
738 /// loading the sync state and the encryption keys from the store, if one
739 /// was set up.
740 ///
741 /// # Persisting the store
742 ///
743 /// Restoring only reattaches the client to its stored state; it does not
744 /// recreate that state. The same persistent store used during the original
745 /// login (for example via [`ClientBuilder::sqlite_store()`]) must be
746 /// configured on the [`ClientBuilder`] when the session is restored,
747 /// otherwise the encryption keys and room state will not be available. When
748 /// the `e2e-encryption` feature is enabled, restoring on top of an
749 /// in-memory store will leave the client unable to send or receive
750 /// encrypted messages. See the [`persist_session`] example for a full
751 /// walk-through.
752 ///
753 /// [`ClientBuilder`]: crate::ClientBuilder
754 /// [`ClientBuilder::sqlite_store()`]: crate::ClientBuilder::sqlite_store
755 /// [`persist_session`]: https://github.com/matrix-org/matrix-rust-sdk/tree/main/examples/persist_session
756 ///
757 /// # Arguments
758 ///
759 /// - `session` - The session to restore.
760 /// - `room_load_settings` — Specify how many rooms must be restored; use
761 /// `::default()` if you don't know which value to pick.
762 ///
763 /// # Panic
764 ///
765 /// Panics if authentication data was already set.
766 pub async fn restore_session(
767 &self,
768 session: OAuthSession,
769 room_load_settings: RoomLoadSettings,
770 ) -> Result<()> {
771 let OAuthSession { client_id, user: UserSession { meta, tokens } } = session;
772
773 let data = OAuthAuthData { client_id, authorization_data: Default::default() };
774
775 self.client.auth_ctx().set_session_tokens(tokens.clone());
776 self.client
777 .activate(
778 meta,
779 room_load_settings,
780 #[cfg(feature = "e2e-encryption")]
781 None,
782 )
783 .await?;
784 #[cfg(feature = "e2e-encryption")]
785 self.deferred_enable_cross_process_refresh_lock().await;
786
787 self.client
788 .inner
789 .auth_ctx
790 .auth_data
791 .set(AuthData::OAuth(data))
792 .expect("Client authentication data was already set");
793
794 // Initialize the cross-process locking by saving our tokens' hash into
795 // the database, if we've enabled the cross-process lock.
796
797 #[cfg(feature = "e2e-encryption")]
798 if let Some(cross_process_lock) = self.ctx().cross_process_token_refresh_manager.get() {
799 cross_process_lock.restore_session(&tokens).await;
800
801 let mut guard = cross_process_lock
802 .spin_lock()
803 .await
804 .map_err(|err| crate::Error::OAuth(Box::new(err.into())))?;
805
806 // After we got the lock, it's possible that our session doesn't
807 // match the one read from the database, because of a race: another
808 // process has refreshed the tokens while we were waiting for the
809 // lock.
810 //
811 // In that case, if there's a mismatch, we reload the session and
812 // update the hash. Otherwise, we save our hash into the database.
813
814 if guard.hash_mismatch {
815 Box::pin(self.handle_session_hash_mismatch(&mut guard))
816 .await
817 .map_err(|err| crate::Error::OAuth(Box::new(err.into())))?;
818 } else {
819 guard
820 .save_in_memory_and_db(&tokens)
821 .await
822 .map_err(|err| crate::Error::OAuth(Box::new(err.into())))?;
823 // No need to call the save_session_callback here; it was the
824 // source of the session, so it's already in sync with what we
825 // had.
826 }
827 }
828
829 #[cfg(feature = "e2e-encryption")]
830 self.client.encryption().spawn_initialization_task(None).await;
831
832 Ok(())
833 }
834
835 #[cfg(feature = "e2e-encryption")]
836 async fn handle_session_hash_mismatch(
837 &self,
838 guard: &mut CrossProcessRefreshLockGuard,
839 ) -> Result<(), CrossProcessRefreshLockError> {
840 trace!("Handling hash mismatch.");
841
842 let callback = self
843 .client
844 .auth_ctx()
845 .reload_session_callback
846 .get()
847 .ok_or(CrossProcessRefreshLockError::MissingReloadSession)?;
848
849 match callback(self.client.clone()) {
850 Ok(tokens) => {
851 guard.handle_mismatch(&tokens).await?;
852
853 self.client.auth_ctx().set_session_tokens(tokens.clone());
854 // The app's callback acted as authoritative here, so we're not
855 // saving the data back into the app, as that would have no
856 // effect.
857 }
858 Err(err) => {
859 error!("when reloading OAuth 2.0 session tokens from callback: {err}");
860 }
861 }
862
863 Ok(())
864 }
865
866 /// The scopes to request for logging in and the corresponding device ID.
867 fn login_scopes(
868 device_id: Option<OwnedDeviceId>,
869 additional_scopes: Option<Vec<Scope>>,
870 ) -> (Vec<Scope>, OwnedDeviceId) {
871 /// Scope to grand full access to the client-server API.
872 const SCOPE_MATRIX_CLIENT_SERVER_API_FULL_ACCESS: &str = "urn:matrix:client:api:*";
873 /// Prefix of the scope to bind a device ID to an access token.
874 const SCOPE_MATRIX_DEVICE_ID_PREFIX: &str = "urn:matrix:client:device:";
875
876 // Generate the device ID if it is not provided.
877 let device_id = device_id.unwrap_or_else(DeviceId::new);
878
879 let mut scopes = vec![
880 Scope::new(SCOPE_MATRIX_CLIENT_SERVER_API_FULL_ACCESS.to_owned()),
881 Scope::new(format!("{SCOPE_MATRIX_DEVICE_ID_PREFIX}{device_id}")),
882 ];
883
884 if let Some(extra_scopes) = additional_scopes {
885 scopes.extend(extra_scopes);
886 }
887
888 (scopes, device_id)
889 }
890
891 /// Log in via OAuth 2.0 with the Authorization Code flow.
892 ///
893 /// This method requires to open a URL in the end-user's browser where they
894 /// will be able to log into their account in the server's web UI and grant
895 /// access to their Matrix account.
896 ///
897 /// The [`OAuthAuthCodeUrlBuilder`] that is returned allows to customize a
898 /// few settings before calling `.build()` to obtain the URL to open in the
899 /// browser of the end-user.
900 ///
901 /// [`OAuth::finish_login()`] must be called once the user has been
902 /// redirected to the `redirect_uri`. [`OAuth::abort_login()`] should be
903 /// called instead if the authorization should be aborted before completion.
904 ///
905 /// # Arguments
906 ///
907 /// - `redirect_uri` - The URI where the end user will be redirected after
908 /// authorizing the login. It must be one of the redirect URIs sent in the
909 /// client metadata during registration.
910 ///
911 /// - `device_id` - The unique ID that will be associated with the session.
912 /// If not set, a random one will be generated. It can be an existing
913 /// device ID from a previous login call. Note that this should be done
914 /// only if the client also holds the corresponding encryption keys.
915 ///
916 /// - `registration_data` - The data to restore or register the client with
917 /// the server. If this is not provided, an error will occur unless
918 /// [`OAuth::register_client()`] or [`OAuth::restore_registered_client()`]
919 /// was called previously.
920 ///
921 /// - `additional_scopes` - Additional scopes to request from the
922 /// authorization server, e.g.
923 /// "urn:matrix:client:com.example.msc9999.foo". The scopes for API access
924 /// and the device ID according to the
925 /// [specification](https://spec.matrix.org/v1.15/client-server-api/#allocated-scope-tokens)
926 /// are always requested.
927 ///
928 /// # Example
929 ///
930 /// ```no_run
931 /// use matrix_sdk::{
932 /// authentication::oauth::registration::ClientMetadata,
933 /// ruma::serde::Raw,
934 /// };
935 /// use url::Url;
936 /// # use matrix_sdk::Client;
937 /// # let client: Client = unimplemented!();
938 /// # let redirect_uri = unimplemented!();
939 /// # async fn open_uri_and_wait_for_redirect(uri: Url) -> Url { unimplemented!() };
940 /// # fn client_metadata() -> Raw<ClientMetadata> { unimplemented!() };
941 /// # _ = async {
942 /// let oauth = client.oauth();
943 /// let client_metadata: Raw<ClientMetadata> = client_metadata();
944 /// let registration_data = client_metadata.into();
945 ///
946 /// let auth_data = oauth.login(redirect_uri, None, Some(registration_data), None)
947 /// .build()
948 /// .await?;
949 ///
950 /// // Open auth_data.url and wait for response at the redirect URI.
951 /// let redirected_to_uri: Url = open_uri_and_wait_for_redirect(auth_data.url).await;
952 ///
953 /// oauth.finish_login(redirected_to_uri.into()).await?;
954 ///
955 /// // The session tokens can be persisted from the
956 /// // `OAuth::full_session()` method.
957 ///
958 /// // You can now make requests to the Matrix API.
959 /// let _me = client.whoami().await?;
960 /// # anyhow::Ok(()) }
961 /// ```
962 pub fn login(
963 &self,
964 redirect_uri: Url,
965 device_id: Option<OwnedDeviceId>,
966 registration_data: Option<ClientRegistrationData>,
967 additional_scopes: Option<Vec<Scope>>,
968 ) -> OAuthAuthCodeUrlBuilder {
969 let (scopes, device_id) = Self::login_scopes(device_id, additional_scopes);
970
971 OAuthAuthCodeUrlBuilder::new(
972 self.clone(),
973 scopes.to_vec(),
974 device_id,
975 redirect_uri,
976 registration_data,
977 )
978 }
979
980 /// Finish the login process.
981 ///
982 /// This method should be called after the URL returned by
983 /// [`OAuthAuthCodeUrlBuilder::build()`] has been presented and the user has
984 /// been redirected to the redirect URI after completing the authorization.
985 ///
986 /// If the authorization needs to be cancelled before its completion,
987 /// [`OAuth::abort_login()`] should be used instead to clean up the local
988 /// data.
989 ///
990 /// # Arguments
991 ///
992 /// - `url_or_query` - The URI where the user was redirected, or just its
993 /// query part.
994 ///
995 /// Returns an error if the authorization failed, if a request fails, or if
996 /// the client was already logged in with a different session.
997 pub async fn finish_login(&self, url_or_query: UrlOrQuery) -> Result<()> {
998 let response = AuthorizationResponse::parse_url_or_query(&url_or_query)
999 .map_err(|error| OAuthError::from(OAuthAuthorizationCodeError::from(error)))?;
1000
1001 let auth_code = match response {
1002 AuthorizationResponse::Success(code) => code,
1003 AuthorizationResponse::Error(error) => {
1004 self.abort_login(&error.state).await;
1005 return Err(OAuthError::from(OAuthAuthorizationCodeError::from(error.error)).into());
1006 }
1007 };
1008
1009 let device_id = self.finish_authorization(auth_code).await?;
1010 self.load_session(device_id).await
1011 }
1012
1013 /// Load the session after login.
1014 ///
1015 /// Returns an error if the request to get the user ID fails, or if the
1016 /// client was already logged in with a different session.
1017 pub(crate) async fn load_session(&self, device_id: OwnedDeviceId) -> Result<()> {
1018 // Get the user ID.
1019 let whoami_res = self.client.whoami().await.map_err(crate::Error::from)?;
1020
1021 let new_session = SessionMeta { user_id: whoami_res.user_id, device_id };
1022
1023 if let Some(current_session) = self.client.session_meta() {
1024 if new_session != *current_session {
1025 return Err(OAuthError::SessionMismatch.into());
1026 }
1027 } else {
1028 self.client
1029 .activate(
1030 new_session,
1031 RoomLoadSettings::default(),
1032 #[cfg(feature = "e2e-encryption")]
1033 None,
1034 )
1035 .await?;
1036 // At this point the Olm machine has been set up.
1037
1038 // Enable the cross-process lock for refreshes, if needs be.
1039 #[cfg(feature = "e2e-encryption")]
1040 self.enable_cross_process_lock().await.map_err(OAuthError::from)?;
1041
1042 #[cfg(feature = "e2e-encryption")]
1043 self.client.encryption().spawn_initialization_task(None).await;
1044 }
1045
1046 Ok(())
1047 }
1048
1049 #[cfg(feature = "e2e-encryption")]
1050 pub(crate) async fn enable_cross_process_lock(
1051 &self,
1052 ) -> Result<(), CrossProcessRefreshLockError> {
1053 // Enable the cross-process lock for refreshes, if needs be.
1054 self.deferred_enable_cross_process_refresh_lock().await;
1055
1056 if let Some(cross_process_manager) = self.ctx().cross_process_token_refresh_manager.get()
1057 && let Some(tokens) = self.client.session_tokens()
1058 {
1059 let mut cross_process_guard = cross_process_manager.spin_lock().await?;
1060
1061 if cross_process_guard.hash_mismatch {
1062 // At this point, we're finishing a login while another process
1063 // had written something in the database. It's likely the
1064 // information in the database is just outdated and wasn't
1065 // properly updated, but display a warning, just in case this
1066 // happens frequently.
1067 warn!("unexpected cross-process hash mismatch when finishing login (see comment)");
1068 }
1069
1070 cross_process_guard.save_in_memory_and_db(&tokens).await?;
1071 }
1072
1073 Ok(())
1074 }
1075
1076 /// Finish the authorization process.
1077 ///
1078 /// This method should be called after the URL returned by
1079 /// [`OAuthAuthCodeUrlBuilder::build()`] has been presented and the user has
1080 /// been redirected to the redirect URI after a successful authorization.
1081 ///
1082 /// # Arguments
1083 ///
1084 /// - `auth_code` - The response received as part of the redirect URI when
1085 /// the authorization was successful.
1086 ///
1087 /// Returns the device ID used in the authorized scope if it succeeds.
1088 /// Returns an error if a request fails.
1089 async fn finish_authorization(
1090 &self,
1091 auth_code: AuthorizationCode,
1092 ) -> Result<OwnedDeviceId, OAuthError> {
1093 let data = self.data().ok_or(OAuthError::NotAuthenticated)?;
1094 let client_id = data.client_id.clone();
1095
1096 let validation_data = data
1097 .authorization_data
1098 .lock()
1099 .await
1100 .remove(&auth_code.state)
1101 .ok_or(OAuthAuthorizationCodeError::InvalidState)?;
1102
1103 let token_uri = TokenUrl::from_url(validation_data.server_metadata.token_endpoint.clone());
1104
1105 let response = OAuthClient::new(client_id)
1106 .set_token_uri(token_uri)
1107 .exchange_code(oauth2::AuthorizationCode::new(auth_code.code))
1108 .set_pkce_verifier(validation_data.pkce_verifier)
1109 .set_redirect_uri(Cow::Owned(validation_data.redirect_uri))
1110 .request_async(self.http_client())
1111 .await
1112 .map_err(OAuthAuthorizationCodeError::RequestToken)?;
1113
1114 self.client.auth_ctx().set_session_tokens(SessionTokens {
1115 access_token: response.access_token().secret().clone(),
1116 refresh_token: response.refresh_token().map(RefreshToken::secret).cloned(),
1117 });
1118
1119 Ok(validation_data.device_id)
1120 }
1121
1122 /// Abort the login process.
1123 ///
1124 /// This method should be called if a login should be aborted before it is
1125 /// completed.
1126 ///
1127 /// If the login has been completed, [`OAuth::finish_login()`] should be
1128 /// used instead.
1129 ///
1130 /// # Arguments
1131 ///
1132 /// - `state` - The state provided in [`OAuthAuthorizationData`] after
1133 /// building the authorization URL.
1134 pub async fn abort_login(&self, state: &CsrfToken) {
1135 if let Some(data) = self.data() {
1136 data.authorization_data.lock().await.remove(state);
1137 }
1138 }
1139
1140 /// Log in via OAuth 2.0 with the Device Authorization Grant.
1141 ///
1142 /// The Device Authorization Grant is defined in [RFC 8628], and its use in
1143 /// Matrix is specified in the [Matrix specification]. This login method is
1144 /// meant for clients that cannot open a browser, or that have limited input
1145 /// capabilities, like bots, bridges, or command-line applications.
1146 ///
1147 /// This registers the client if necessary, and requests the authorization
1148 /// from the authorization server. The returned [`DeviceCodeLogin`]
1149 /// provides the verification URI and the user code. They must be presented
1150 /// to the end-user, who will need to open the URI in a browser on another
1151 /// device, log into their account in the server's web UI and grant access
1152 /// to their Matrix account. Meanwhile, [`DeviceCodeLogin::finish()`] must
1153 /// be called to wait for the authorization and complete the login.
1154 ///
1155 /// # Arguments
1156 ///
1157 /// - `device_id` - The unique ID that will be associated with the session.
1158 /// If not set, a random one will be generated. It can be an existing
1159 /// device ID from a previous login call. Note that this should be done
1160 /// only if the client also holds the corresponding encryption keys.
1161 ///
1162 /// - `registration_data` - The data to restore or register the client with
1163 /// the server. If this is not provided, an error will occur unless
1164 /// [`OAuth::register_client()`] or [`OAuth::restore_registered_client()`]
1165 /// was called previously. If the client is registered with this data, the
1166 /// [`OAuthGrantType::DeviceCode`] grant type is added to the client
1167 /// metadata if it is missing.
1168 ///
1169 /// - `additional_scopes` - Additional scopes to request from the
1170 /// authorization server, e.g.
1171 /// "urn:matrix:client:com.example.msc9999.foo". The scopes for API access
1172 /// and the device ID according to the
1173 /// [specification](https://spec.matrix.org/v1.15/client-server-api/#allocated-scope-tokens)
1174 /// are always requested.
1175 ///
1176 /// # Example
1177 ///
1178 /// ```no_run
1179 /// # use matrix_sdk::Client;
1180 /// # let client: Client = unimplemented!();
1181 /// # _ = async {
1182 /// let login = client.oauth().login_with_device_code(None, None, None).await?;
1183 ///
1184 /// println!(
1185 /// "Open {} and enter the code {}",
1186 /// login.verification_uri(),
1187 /// login.user_code()
1188 /// );
1189 ///
1190 /// login.finish().await?;
1191 /// # anyhow::Ok(()) };
1192 /// ```
1193 ///
1194 /// See the [`oauth_device_code`] example for a complete program, including
1195 /// the client registration.
1196 ///
1197 /// [`oauth_device_code`]: https://github.com/matrix-org/matrix-rust-sdk/tree/main/examples/oauth_device_code
1198 /// [RFC 8628]: https://datatracker.ietf.org/doc/html/rfc8628
1199 /// [Matrix specification]: https://spec.matrix.org/v1.19/client-server-api/#device-authorisation-flow
1200 /// [`OAuthGrantType::DeviceCode`]: registration::OAuthGrantType::DeviceCode
1201 pub async fn login_with_device_code(
1202 &self,
1203 device_id: Option<OwnedDeviceId>,
1204 registration_data: Option<ClientRegistrationData>,
1205 additional_scopes: Option<Vec<Scope>>,
1206 ) -> Result<DeviceCodeLogin, DeviceCodeLoginError> {
1207 let (scopes, device_id) = Self::login_scopes(device_id, additional_scopes);
1208 DeviceCodeLogin::start(self.clone(), scopes, device_id, registration_data).await
1209 }
1210
1211 /// Request codes from the authorization server for logging in with the
1212 /// device authorization grant ([RFC 8628]).
1213 ///
1214 /// The `scopes` should be computed with [`OAuth::login_scopes()`].
1215 ///
1216 /// [RFC 8628]: https://datatracker.ietf.org/doc/html/rfc8628
1217 async fn request_device_authorization(
1218 &self,
1219 server_metadata: &AuthorizationServerMetadata,
1220 scopes: Vec<Scope>,
1221 ) -> Result<oauth2::StandardDeviceAuthorizationResponse, DeviceAuthorizationOAuthError> {
1222 let client_id = self.client_id().ok_or(OAuthError::NotRegistered)?.clone();
1223
1224 let device_authorization_url = server_metadata
1225 .device_authorization_endpoint
1226 .clone()
1227 .map(oauth2::DeviceAuthorizationUrl::from_url)
1228 .ok_or(DeviceAuthorizationOAuthError::NoDeviceAuthorizationEndpoint)?;
1229
1230 let response = OAuthClient::new(client_id)
1231 .set_device_authorization_url(device_authorization_url)
1232 .exchange_device_code()
1233 .add_scopes(scopes)
1234 .request_async(self.http_client())
1235 .await?;
1236
1237 Ok(response)
1238 }
1239
1240 /// Exchange the device code against an access token.
1241 ///
1242 /// This polls the token endpoint until the user approves or denies the
1243 /// authorization request, or until the device code expires. On success,
1244 /// the session tokens are set on the client.
1245 async fn exchange_device_code(
1246 &self,
1247 server_metadata: &AuthorizationServerMetadata,
1248 device_authorization_response: &oauth2::StandardDeviceAuthorizationResponse,
1249 ) -> Result<(), DeviceAuthorizationOAuthError> {
1250 let client_id = self.client_id().ok_or(OAuthError::NotRegistered)?.clone();
1251
1252 let token_uri = TokenUrl::from_url(server_metadata.token_endpoint.clone());
1253
1254 let response = OAuthClient::new(client_id)
1255 .set_token_uri(token_uri)
1256 .exchange_device_access_token(device_authorization_response)
1257 .request_async(self.http_client(), matrix_sdk_common::sleep::sleep, None)
1258 .await?;
1259
1260 self.client.auth_ctx().set_session_tokens(SessionTokens {
1261 access_token: response.access_token().secret().to_owned(),
1262 refresh_token: response.refresh_token().map(|t| t.secret().to_owned()),
1263 });
1264
1265 Ok(())
1266 }
1267
1268 async fn refresh_access_token_inner(
1269 self,
1270 refresh_token: String,
1271 token_endpoint: Url,
1272 client_id: ClientId,
1273 #[cfg(feature = "e2e-encryption")] cross_process_lock: Option<CrossProcessRefreshLockGuard>,
1274 ) -> Result<(), OAuthError> {
1275 trace!(
1276 "Token refresh: attempting to refresh with refresh_token {}",
1277 hash_str(&refresh_token)
1278 );
1279
1280 let token = RefreshToken::new(refresh_token.clone());
1281 let token_uri = TokenUrl::from_url(token_endpoint);
1282
1283 let response = OAuthClient::new(client_id)
1284 .set_token_uri(token_uri)
1285 .exchange_refresh_token(&token)
1286 .request_async(self.http_client())
1287 .await
1288 .map_err(OAuthError::RefreshToken)?;
1289
1290 let new_access_token = response.access_token().secret().clone();
1291 let new_refresh_token = response.refresh_token().map(RefreshToken::secret).cloned();
1292
1293 trace!(
1294 "Token refresh: new refresh_token: {} / access_token: {}",
1295 new_refresh_token.as_deref().map(hash_str).unwrap_or_else(|| "<none>".to_owned()),
1296 hash_str(&new_access_token)
1297 );
1298
1299 let tokens = SessionTokens {
1300 access_token: new_access_token,
1301 refresh_token: new_refresh_token.or(Some(refresh_token)),
1302 };
1303
1304 #[cfg(feature = "e2e-encryption")]
1305 let tokens_clone = tokens.clone();
1306
1307 self.client.auth_ctx().set_session_tokens(tokens);
1308
1309 // Call the save_session_callback if set, while the optional lock is
1310 // being held.
1311 if let Some(save_session_callback) = self.client.auth_ctx().save_session_callback.get() {
1312 // Satisfies the save_session_callback invariant: set_session_tokens
1313 // has been called just above.
1314 tracing::debug!("call save_session_callback");
1315 if let Err(err) = save_session_callback(self.client.clone()) {
1316 error!("when saving session after refresh: {err}");
1317 }
1318 }
1319
1320 #[cfg(feature = "e2e-encryption")]
1321 if let Some(mut lock) = cross_process_lock {
1322 lock.save_in_memory_and_db(&tokens_clone).await?;
1323 }
1324
1325 tracing::debug!("broadcast session changed");
1326 _ = self.client.auth_ctx().session_change_sender.send(SessionChange::TokensRefreshed);
1327
1328 Ok(())
1329 }
1330
1331 /// Refresh the access token.
1332 ///
1333 /// This should be called when the access token has expired. It should not
1334 /// be needed to call this manually if the [`Client`] was constructed with
1335 /// [`ClientBuilder::handle_refresh_tokens()`].
1336 ///
1337 /// This method is protected behind a lock, so calling this method several
1338 /// times at once will only call the endpoint once and all subsequent calls
1339 /// will wait for the result of the first call.
1340 ///
1341 /// [`ClientBuilder::handle_refresh_tokens()`]: crate::ClientBuilder::handle_refresh_tokens()
1342 #[instrument(skip_all)]
1343 pub async fn refresh_access_token(&self) -> Result<(), RefreshTokenError> {
1344 macro_rules! fail {
1345 ($lock:expr, $err:expr) => {
1346 let error = $err;
1347 *$lock = Err(error.clone());
1348 return Err(error);
1349 };
1350 }
1351
1352 let client = &self.client;
1353
1354 let refresh_status_lock = client.auth_ctx().refresh_token_lock.clone().try_lock_owned();
1355
1356 let Ok(mut refresh_status_guard) = refresh_status_lock else {
1357 debug!("another refresh is happening, waiting for result.");
1358 // There's already a request to refresh happening in the same
1359 // process. Wait for it to finish.
1360 let res = client.auth_ctx().refresh_token_lock.lock().await.clone();
1361 debug!("other refresh is a {}", if res.is_ok() { "success" } else { "failure " });
1362 return res;
1363 };
1364
1365 debug!("no other refresh happening in background, starting.");
1366
1367 // Fetch the authorization server metadata _before_ taking the
1368 // cross-process lock, checking the session hash, or reading the refresh
1369 // token. This request can stall for a long time when the OS suspends
1370 // the process (e.g. iOS background suspension), and while suspended the
1371 // lock lease lapses, which lets another process refresh and rotate the
1372 // token. Doing it first means the lock and the hash check happen after
1373 // the stall, so such a rotation is caught below as a hash mismatch
1374 // instead of being exchanged while stale, which the server rejects with
1375 // `invalid_grant` and signs the user out.
1376 let server_metadata = match self.server_metadata().await {
1377 Ok(metadata) => metadata,
1378 Err(err) => {
1379 warn!("couldn't get authorization server metadata: {err:?}");
1380 fail!(refresh_status_guard, RefreshTokenError::OAuth(Arc::new(err.into())));
1381 }
1382 };
1383
1384 let Some(client_id) = self.client_id().cloned() else {
1385 warn!("invalid state: missing client ID");
1386 fail!(
1387 refresh_status_guard,
1388 RefreshTokenError::OAuth(Arc::new(OAuthError::NotAuthenticated))
1389 );
1390 };
1391
1392 #[cfg(feature = "e2e-encryption")]
1393 let cross_process_guard =
1394 if let Some(manager) = self.ctx().cross_process_token_refresh_manager.get() {
1395 let mut cross_process_guard = match manager
1396 .spin_lock()
1397 .await
1398 .map_err(|err| RefreshTokenError::OAuth(Arc::new(err.into())))
1399 {
1400 Ok(guard) => guard,
1401 Err(err) => {
1402 warn!("couldn't acquire cross-process lock (timeout)");
1403 fail!(refresh_status_guard, err);
1404 }
1405 };
1406
1407 if cross_process_guard.hash_mismatch {
1408 Box::pin(self.handle_session_hash_mismatch(&mut cross_process_guard))
1409 .await
1410 .map_err(|err| RefreshTokenError::OAuth(Arc::new(err.into())))?;
1411 // Optimistic exit: assume that the underlying process did
1412 // update fast enough. In the worst case, we'll do another
1413 // refresh Soon™.
1414 tracing::info!("other process handled refresh for us, assuming success");
1415 *refresh_status_guard = Ok(());
1416 return Ok(());
1417 }
1418
1419 Some(cross_process_guard)
1420 } else {
1421 None
1422 };
1423
1424 // Read the refresh token only now, after the hash check above, so we
1425 // always exchange the token that is current in the store, never one
1426 // that another process rotated out from under us while we were
1427 // suspended.
1428 let Some(session_tokens) = self.client.session_tokens() else {
1429 warn!("invalid state: missing session tokens");
1430 fail!(refresh_status_guard, RefreshTokenError::RefreshTokenRequired);
1431 };
1432
1433 let Some(refresh_token) = session_tokens.refresh_token else {
1434 warn!("invalid state: missing session tokens");
1435 fail!(refresh_status_guard, RefreshTokenError::RefreshTokenRequired);
1436 };
1437
1438 // Do not interrupt refresh access token requests and processing, by
1439 // detaching the request sending and response processing. Make sure to
1440 // keep the `refresh_status_guard` during the entire processing.
1441
1442 let this = self.clone();
1443
1444 spawn(async move {
1445 match this
1446 .refresh_access_token_inner(
1447 refresh_token,
1448 server_metadata.token_endpoint,
1449 client_id,
1450 #[cfg(feature = "e2e-encryption")]
1451 cross_process_guard,
1452 )
1453 .await
1454 {
1455 Ok(()) => {
1456 debug!("success refreshing a token");
1457 *refresh_status_guard = Ok(());
1458 Ok(())
1459 }
1460
1461 Err(err) => {
1462 let err = RefreshTokenError::OAuth(Arc::new(err));
1463 warn!("error refreshing an OAuth 2.0 token: {err}");
1464 fail!(refresh_status_guard, err);
1465 }
1466 }
1467 })
1468 .await
1469 .expect("joining")
1470 }
1471
1472 /// Log out from the currently authenticated session.
1473 pub async fn logout(&self) -> Result<(), OAuthError> {
1474 let client_id = self.client_id().ok_or(OAuthError::NotAuthenticated)?.clone();
1475
1476 let server_metadata = self.server_metadata().await?;
1477 let revocation_url = RevocationUrl::from_url(server_metadata.revocation_endpoint);
1478
1479 let tokens = self.client.session_tokens().ok_or(OAuthError::NotAuthenticated)?;
1480
1481 // Revoke the access token, it should revoke both tokens.
1482 OAuthClient::new(client_id)
1483 .set_revocation_url(revocation_url)
1484 .revoke_token(StandardRevocableToken::AccessToken(AccessToken::new(
1485 tokens.access_token,
1486 )))
1487 .map_err(OAuthTokenRevocationError::Url)?
1488 .request_async(self.http_client())
1489 .await
1490 .map_err(OAuthTokenRevocationError::Revoke)?;
1491
1492 #[cfg(feature = "e2e-encryption")]
1493 if let Some(manager) = self.ctx().cross_process_token_refresh_manager.get() {
1494 manager.on_logout().await?;
1495 }
1496
1497 Ok(())
1498 }
1499}
1500
1501/// Builder for QR login futures.
1502#[cfg(feature = "e2e-encryption")]
1503#[derive(Debug)]
1504pub struct LoginWithQrCodeBuilder<'a> {
1505 /// The underlying Matrix API client.
1506 client: &'a Client,
1507
1508 /// The data to restore or register the client with the server.
1509 registration_data: Option<&'a ClientRegistrationData>,
1510}
1511
1512#[cfg(feature = "e2e-encryption")]
1513impl<'a> LoginWithQrCodeBuilder<'a> {
1514 /// Create a new builder.
1515 fn new(client: &'a Client, registration_data: Option<&'a ClientRegistrationData>) -> Self {
1516 Self { client, registration_data }
1517 }
1518
1519 /// This method allows you to log in with a scanned QR code.
1520 ///
1521 /// The existing device needs to display the QR code which this device can
1522 /// scan and call this method to log in.
1523 ///
1524 /// A successful login using this method will automatically mark the device
1525 /// as verified and transfer all end-to-end encryption related secrets, like
1526 /// the private cross-signing keys and the backup key from the existing
1527 /// device to the new device.
1528 ///
1529 /// For the reverse flow where this device generates the QR code for the
1530 /// existing device to scan, use [`LoginWithQrCodeBuilder::generate`].
1531 ///
1532 /// # Arguments
1533 ///
1534 /// - `data` - The data scanned from a QR code.
1535 ///
1536 /// # Example
1537 ///
1538 /// ```no_run
1539 /// use anyhow::bail;
1540 /// use futures_util::StreamExt;
1541 /// use matrix_sdk::{
1542 /// authentication::oauth::{
1543 /// registration::ClientMetadata,
1544 /// qrcode::{LoginProgress, Msc4108IntentData, QrCodeData, QrCodeIntentData, QrProgress},
1545 /// },
1546 /// ruma::serde::Raw,
1547 /// Client,
1548 /// };
1549 /// # fn client_metadata() -> Raw<ClientMetadata> { unimplemented!() }
1550 /// # _ = async {
1551 /// # let bytes = unimplemented!();
1552 /// // You'll need to use a different library to scan and extract the raw bytes from the QR
1553 /// // code.
1554 /// let qr_code_data = QrCodeData::from_bytes(bytes)?;
1555 ///
1556 /// // Fetch the homeserver out of the parsed QR code data.
1557 /// let QrCodeIntentData::Msc4108 { data: Msc4108IntentData::Reciprocate { server_name }, ..} = qr_code_data.intent_data() else {
1558 /// bail!("The QR code is invalid, we did not receive a homeserver in the QR code.");
1559 /// };
1560 ///
1561 /// // Build the client as usual.
1562 /// let client = Client::builder()
1563 /// .server_name_or_homeserver_url(server_name)
1564 /// .handle_refresh_tokens()
1565 /// .build()
1566 /// .await?;
1567 ///
1568 /// let oauth = client.oauth();
1569 /// let client_metadata: Raw<ClientMetadata> = client_metadata();
1570 /// let registration_data = client_metadata.into();
1571 ///
1572 /// // Subscribing to the progress is necessary since we need to input the check
1573 /// // code on the existing device.
1574 /// let login = oauth.login_with_qr_code(Some(®istration_data)).scan(&qr_code_data);
1575 /// let mut progress = login.subscribe_to_progress();
1576 ///
1577 /// // Create a task which will show us the progress and tell us the check
1578 /// // code to input in the existing device.
1579 /// let task = tokio::spawn(async move {
1580 /// while let Some(state) = progress.next().await {
1581 /// match state {
1582 /// LoginProgress::Starting | LoginProgress::SyncingSecrets => (),
1583 /// LoginProgress::EstablishingSecureChannel(QrProgress { check_code }) => {
1584 /// println!("Please enter the following code into the other device {check_code:02}");
1585 /// },
1586 /// LoginProgress::WaitingForToken { user_code } => {
1587 /// println!("Please use your other device to confirm the log in {user_code}")
1588 /// },
1589 /// LoginProgress::Done => break,
1590 /// }
1591 /// }
1592 /// });
1593 ///
1594 /// // Now run the future to complete the login.
1595 /// login.await?;
1596 /// task.abort();
1597 ///
1598 /// println!("Successfully logged in: {:?} {:?}", client.user_id(), client.device_id());
1599 /// # anyhow::Ok(()) };
1600 /// ```
1601 pub fn scan(self, data: &QrCodeData) -> LoginWithQrCode {
1602 LoginWithQrCode::new(self.client, data, self.registration_data)
1603 }
1604
1605 /// This method allows you to log in by generating a QR code.
1606 ///
1607 /// This device needs to call this method to generate and display the QR
1608 /// code which the existing device can scan and grant the log in.
1609 ///
1610 /// A successful login using this method will automatically mark the device
1611 /// as verified and transfer all end-to-end encryption related secrets, like
1612 /// the private cross-signing keys and the backup key from the existing
1613 /// device to the new device.
1614 ///
1615 /// For the reverse flow where the existing device generates the QR code for
1616 /// this device to scan, use [`LoginWithQrCodeBuilder::scan`].
1617 ///
1618 /// # Example
1619 ///
1620 /// ```no_run
1621 /// use anyhow::bail;
1622 /// use futures_util::StreamExt;
1623 /// use matrix_sdk::{
1624 /// authentication::oauth::{
1625 /// registration::ClientMetadata,
1626 /// qrcode::{GeneratedQrProgress, LoginProgress, QrCodeData},
1627 /// },
1628 /// ruma::serde::Raw,
1629 /// Client,
1630 /// };
1631 /// use std::{error::Error, io::stdin};
1632 /// # fn client_metadata() -> Raw<ClientMetadata> { unimplemented!() }
1633 /// # _ = async {
1634 /// // Build the client as usual.
1635 /// let client = Client::builder()
1636 /// .server_name_or_homeserver_url("matrix.org")
1637 /// .handle_refresh_tokens()
1638 /// .build()
1639 /// .await?;
1640 ///
1641 /// let oauth = client.oauth();
1642 /// let client_metadata: Raw<ClientMetadata> = client_metadata();
1643 /// let registration_data = client_metadata.into();
1644 ///
1645 /// // Subscribing to the progress is necessary since we need to display the
1646 /// // QR code and prompt for the check code.
1647 /// let login = oauth.login_with_qr_code(Some(®istration_data)).generate();
1648 /// let mut progress = login.subscribe_to_progress();
1649 ///
1650 /// // Create a task which will show us the progress and allows us to display
1651 /// // the QR code and prompt for the check code.
1652 /// let task = tokio::spawn(async move {
1653 /// while let Some(state) = progress.next().await {
1654 /// match state {
1655 /// LoginProgress::Starting | LoginProgress::SyncingSecrets => (),
1656 /// LoginProgress::EstablishingSecureChannel(GeneratedQrProgress::QrReady(qr)) => {
1657 /// println!("Please use your other device to scan the QR code {:?}", qr)
1658 /// }
1659 /// LoginProgress::EstablishingSecureChannel(GeneratedQrProgress::QrScanned(cctx)) => {
1660 /// println!("Please enter the code displayed on your other device");
1661 /// let mut s = String::new();
1662 /// stdin().read_line(&mut s)?;
1663 /// let check_code = s.trim().parse::<u8>()?;
1664 /// cctx.send(check_code).await?
1665 /// }
1666 /// LoginProgress::WaitingForToken { user_code } => {
1667 /// println!("Please use your other device to confirm the log in {user_code}")
1668 /// },
1669 /// LoginProgress::Done => break,
1670 /// }
1671 /// }
1672 /// Ok::<(), Box<dyn Error + Send + Sync>>(())
1673 /// });
1674 ///
1675 /// // Now run the future to complete the login.
1676 /// login.await?;
1677 /// task.abort();
1678 ///
1679 /// println!("Successfully logged in: {:?} {:?}", client.user_id(), client.device_id());
1680 /// # anyhow::Ok(()) };
1681 /// ```
1682 pub fn generate(self) -> LoginWithGeneratedQrCode {
1683 LoginWithGeneratedQrCode::new(self.client, self.registration_data)
1684 }
1685}
1686
1687/// Builder for QR login grant handlers.
1688#[cfg(feature = "e2e-encryption")]
1689#[derive(Debug)]
1690pub struct GrantLoginWithQrCodeBuilder<'a> {
1691 /// The underlying Matrix API client.
1692 client: &'a Client,
1693 /// The duration to wait for the homeserver to create the new device after
1694 /// consenting the login before giving up.
1695 device_creation_timeout: Duration,
1696}
1697
1698#[cfg(feature = "e2e-encryption")]
1699impl<'a> GrantLoginWithQrCodeBuilder<'a> {
1700 /// Create a new builder with the default device creation timeout.
1701 fn new(client: &'a Client) -> Self {
1702 Self { client, device_creation_timeout: Duration::from_secs(10) }
1703 }
1704
1705 /// Set the device creation timeout.
1706 ///
1707 /// # Arguments
1708 ///
1709 /// - `device_creation_timeout` - The duration to wait for the homeserver to
1710 /// create the new device after consenting the login before giving up.
1711 pub fn device_creation_timeout(mut self, device_creation_timeout: Duration) -> Self {
1712 self.device_creation_timeout = device_creation_timeout;
1713 self
1714 }
1715
1716 /// This method allows you to grant login to a new device by scanning a QR
1717 /// code generated by the new device.
1718 ///
1719 /// The new device needs to display the QR code which this device can scan
1720 /// and call this method to grant the login.
1721 ///
1722 /// A successful login grant using this method will automatically mark the
1723 /// new device as verified and transfer all end-to-end encryption related
1724 /// secrets, like the private cross-signing keys and the backup key from
1725 /// this device device to the new device.
1726 ///
1727 /// For the reverse flow where this device generates the QR code for the new
1728 /// device to scan, use [`GrantLoginWithQrCodeBuilder::generate`].
1729 ///
1730 /// # Arguments
1731 ///
1732 /// - `data` - The data scanned from a QR code.
1733 ///
1734 /// # Example
1735 ///
1736 /// ```no_run
1737 /// use anyhow::bail;
1738 /// use futures_util::StreamExt;
1739 /// use matrix_sdk::{
1740 /// Client, authentication::oauth::{
1741 /// qrcode::{GrantLoginProgress, QrCodeData, QrProgress},
1742 /// }
1743 /// };
1744 /// use std::{error::Error, io::stdin};
1745 /// # _ = async {
1746 /// # let bytes = unimplemented!();
1747 /// // You'll need to use a different library to scan and extract the raw bytes from the QR
1748 /// // code.
1749 /// let qr_code_data = QrCodeData::from_bytes(bytes)?;
1750 ///
1751 /// // Build the client as usual.
1752 /// let client = Client::builder()
1753 /// .server_name_or_homeserver_url("matrix.org")
1754 /// .handle_refresh_tokens()
1755 /// .build()
1756 /// .await?;
1757 ///
1758 /// let oauth = client.oauth();
1759 ///
1760 /// // Subscribing to the progress is necessary to capture
1761 /// // the checkcode in order to display it to the other device and to obtain the verification URL to
1762 /// // open it in a browser so the user can consent to the new login.
1763 /// let mut grant = oauth.grant_login_with_qr_code().scan(&qr_code_data);
1764 /// let mut progress = grant.subscribe_to_progress();
1765 ///
1766 /// // Create a task which will show us the progress and allows us to receive
1767 /// // and feed back data.
1768 /// let task = tokio::spawn(async move {
1769 /// while let Some(state) = progress.next().await {
1770 /// match state {
1771 /// GrantLoginProgress::Starting | GrantLoginProgress::SyncingSecrets => (),
1772 /// GrantLoginProgress::EstablishingSecureChannel(QrProgress { check_code }) => {
1773 /// println!("Please enter the checkcode on your other device: {:?}", check_code);
1774 /// }
1775 /// GrantLoginProgress::WaitingForAuth { verification_uri, continuation_sender } => {
1776 /// println!("Please open {verification_uri} to confirm the new login");
1777 ///
1778 /// // Once the new login has been confirmed in the browser, we can let the
1779 /// // client continue with the process.
1780 /// continuation_sender.confirm().await?;
1781 /// },
1782 /// GrantLoginProgress::Done => break,
1783 /// }
1784 /// }
1785 /// Ok::<(), Box<dyn Error + Send + Sync>>(())
1786 /// });
1787 ///
1788 /// // Now run the future to grant the login.
1789 /// grant.await?;
1790 /// task.abort();
1791 ///
1792 /// println!("Successfully granted login");
1793 /// # anyhow::Ok(()) };
1794 /// ```
1795 pub fn scan(self, data: &QrCodeData) -> GrantLoginWithScannedQrCode {
1796 GrantLoginWithScannedQrCode::new(self.client, data, self.device_creation_timeout)
1797 }
1798
1799 /// This method allows you to grant login to a new device by generating a QR
1800 /// code on this device to be scanned by the new device.
1801 ///
1802 /// This device needs to call this method to generate and display the QR
1803 /// code which the new device can scan to initiate the grant process.
1804 ///
1805 /// A successful login grant using this method will automatically mark the
1806 /// new device as verified and transfer all end-to-end encryption related
1807 /// secrets, like the private cross-signing keys and the backup key from
1808 /// this device device to the new device.
1809 ///
1810 /// For the reverse flow where the new device generates the QR code for this
1811 /// device to scan, use [`GrantLoginWithQrCodeBuilder::scan`].
1812 ///
1813 /// # Example
1814 ///
1815 /// ```no_run
1816 /// use anyhow::bail;
1817 /// use futures_util::StreamExt;
1818 /// use matrix_sdk::{
1819 /// Client, authentication::oauth::{
1820 /// qrcode::{GeneratedQrProgress, GrantLoginProgress}
1821 /// }
1822 /// };
1823 /// use std::{error::Error, io::stdin};
1824 /// # _ = async {
1825 /// // Build the client as usual.
1826 /// let client = Client::builder()
1827 /// .server_name_or_homeserver_url("matrix.org")
1828 /// .handle_refresh_tokens()
1829 /// .build()
1830 /// .await?;
1831 ///
1832 /// let oauth = client.oauth();
1833 ///
1834 /// // Subscribing to the progress is necessary since we need to capture the
1835 /// // QR code, feed the checkcode back in and obtain the verification URL to
1836 /// // open it in a browser so the user can consent to the new login.
1837 /// let mut grant = oauth.grant_login_with_qr_code().generate();
1838 /// let mut progress = grant.subscribe_to_progress();
1839 ///
1840 /// // Create a task which will show us the progress and allows us to receive
1841 /// // and feed back data.
1842 /// let task = tokio::spawn(async move {
1843 /// while let Some(state) = progress.next().await {
1844 /// match state {
1845 /// GrantLoginProgress::Starting | GrantLoginProgress::SyncingSecrets => (),
1846 /// GrantLoginProgress::EstablishingSecureChannel(GeneratedQrProgress::QrReady(qr_code_data)) => {
1847 /// println!("Please scan the QR code on your other device: {:?}", qr_code_data);
1848 /// }
1849 /// GrantLoginProgress::EstablishingSecureChannel(GeneratedQrProgress::QrScanned(checkcode_sender)) => {
1850 /// println!("Please enter the code displayed on your other device");
1851 /// let mut s = String::new();
1852 /// stdin().read_line(&mut s)?;
1853 /// let check_code = s.trim().parse::<u8>()?;
1854 /// checkcode_sender.send(check_code).await?;
1855 /// }
1856 /// GrantLoginProgress::WaitingForAuth { verification_uri, continuation_sender } => {
1857 /// println!("Please open {verification_uri} to confirm the new login");
1858 ///
1859 /// // Once the new login has been confirmed in the browser, we can let the
1860 /// // client continue with the process.
1861 /// continuation_sender.confirm().await?;
1862 /// },
1863 /// GrantLoginProgress::Done => break,
1864 /// }
1865 /// }
1866 /// Ok::<(), Box<dyn Error + Send + Sync>>(())
1867 /// });
1868 ///
1869 /// // Now run the future to grant the login.
1870 /// grant.await?;
1871 /// task.abort();
1872 ///
1873 /// println!("Successfully granted login");
1874 /// # anyhow::Ok(()) };
1875 /// ```
1876 pub fn generate(self) -> GrantLoginWithGeneratedQrCode {
1877 GrantLoginWithGeneratedQrCode::new(self.client, self.device_creation_timeout)
1878 }
1879}
1880/// A full session for the OAuth 2.0 API.
1881#[derive(Debug, Clone, Serialize, Deserialize)]
1882pub struct OAuthSession {
1883 /// The client ID obtained after registration.
1884 pub client_id: ClientId,
1885
1886 /// The user session.
1887 #[serde(flatten)]
1888 pub user: UserSession,
1889}
1890
1891/// A user session for the OAuth 2.0 API.
1892#[derive(Debug, Clone, Serialize, Deserialize)]
1893pub struct UserSession {
1894 /// The Matrix user session info.
1895 #[serde(flatten)]
1896 pub meta: SessionMeta,
1897
1898 /// The tokens used for authentication.
1899 #[serde(flatten)]
1900 pub tokens: SessionTokens,
1901}
1902
1903/// The data necessary to validate a response from the Token endpoint in the
1904/// Authorization Code flow.
1905#[derive(Debug)]
1906struct AuthorizationValidationData {
1907 /// The metadata of the server,
1908 server_metadata: AuthorizationServerMetadata,
1909
1910 /// The device ID used in the scope.
1911 device_id: OwnedDeviceId,
1912
1913 /// The URI where the end-user will be redirected after authorization.
1914 redirect_uri: RedirectUrl,
1915
1916 /// A string to correlate the authorization request to the token request.
1917 pkce_verifier: PkceCodeVerifier,
1918}
1919
1920/// The data returned by the server in the redirect URI after a successful
1921/// authorization.
1922#[derive(Debug, Clone)]
1923enum AuthorizationResponse {
1924 /// A successful response.
1925 Success(AuthorizationCode),
1926
1927 /// An error response.
1928 Error(AuthorizationError),
1929}
1930
1931impl AuthorizationResponse {
1932 /// Deserialize an `AuthorizationResponse` from a [`UrlOrQuery`].
1933 ///
1934 /// Returns an error if the URL or query doesn't have the expected format.
1935 fn parse_url_or_query(url_or_query: &UrlOrQuery) -> Result<Self, RedirectUriQueryParseError> {
1936 let query = url_or_query.query().ok_or(RedirectUriQueryParseError::MissingQuery)?;
1937 Self::parse_query(query)
1938 }
1939
1940 /// Deserialize an `AuthorizationResponse` from the query part of a URI.
1941 ///
1942 /// Returns an error if the query doesn't have the expected format.
1943 fn parse_query(query: &str) -> Result<Self, RedirectUriQueryParseError> {
1944 // For some reason deserializing the enum with `serde(untagged)` doesn't
1945 // work, so let's try both variants separately.
1946 if let Ok(code) = serde_html_form::from_str(query) {
1947 return Ok(AuthorizationResponse::Success(code));
1948 }
1949 if let Ok(error) = serde_html_form::from_str(query) {
1950 return Ok(AuthorizationResponse::Error(error));
1951 }
1952
1953 Err(RedirectUriQueryParseError::UnknownFormat)
1954 }
1955}
1956
1957/// The data returned by the server in the redirect URI after a successful
1958/// authorization.
1959#[derive(Debug, Clone, Deserialize)]
1960struct AuthorizationCode {
1961 /// The code to use to retrieve the access token.
1962 code: String,
1963 /// The unique identifier for this transaction.
1964 state: CsrfToken,
1965}
1966
1967/// The data returned by the server in the redirect URI after an authorization
1968/// error.
1969#[derive(Debug, Clone, Deserialize)]
1970struct AuthorizationError {
1971 /// The error.
1972 #[serde(flatten)]
1973 error: StandardErrorResponse<error::AuthorizationCodeErrorResponseType>,
1974 /// The unique identifier for this transaction.
1975 state: CsrfToken,
1976}
1977
1978fn hash_str(x: &str) -> String {
1979 hex::encode(sha2::Sha256::new().chain_update(x).finalize())
1980}
1981
1982/// Data to register or restore a client.
1983#[derive(Debug, Clone)]
1984pub struct ClientRegistrationData {
1985 /// The metadata to use to register the client when using dynamic client
1986 /// registration.
1987 pub metadata: Raw<ClientMetadata>,
1988
1989 /// Static registrations for servers that don't support dynamic registration
1990 /// but provide a client ID out-of-band.
1991 ///
1992 /// The keys of the map should be the URLs of the homeservers, but keys
1993 /// using `issuer` URLs are also supported.
1994 pub static_registrations: Option<HashMap<Url, ClientId>>,
1995}
1996
1997impl ClientRegistrationData {
1998 /// Construct a [`ClientRegistrationData`] with the given metadata and no
1999 /// static registrations.
2000 pub fn new(metadata: Raw<ClientMetadata>) -> Self {
2001 Self { metadata, static_registrations: None }
2002 }
2003}
2004
2005impl From<Raw<ClientMetadata>> for ClientRegistrationData {
2006 fn from(value: Raw<ClientMetadata>) -> Self {
2007 Self::new(value)
2008 }
2009}