matrix_sdk/authentication/oauth/
mod.rs

1// Copyright 2022 Kévin Commaille
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//! High-level OAuth 2.0 API.
16//!
17//! The OAuth 2.0 interactions with the Matrix API are currently a
18//! work-in-progress and are defined by [MSC3861] and its sub-proposals. And
19//! more documentation is available at [areweoidcyet.com].
20//!
21//! This authentication API is available with [`Client::oauth()`].
22//!
23//! # Homeserver support
24//!
25//! After building the client, you can check that the homeserver supports
26//! logging in via OAuth 2.0 when [`OAuth::server_metadata()`] succeeds.
27//!
28//! # Registration
29//!
30//! Clients must register with the homeserver before being able to interact with
31//! an OAuth 2.0 server.
32//!
33//! The registration consists in providing client metadata to the authorization
34//! server, to declare the interactions that the client supports with the
35//! homeserver. This step is important because the client cannot use a feature
36//! that is not declared during registration. In return, the server assigns an
37//! ID and eventually credentials to the client, which will allow to identify
38//! the client when authorization requests are made.
39//!
40//! Note that only public clients are supported by this API, i.e. clients
41//! without credentials.
42//!
43//! The registration step can be done automatically by providing a
44//! [`ClientRegistrationData`] to the login method.
45//!
46//! If the server supports dynamic registration, registration can be performed
47//! manually by using [`OAuth::register_client()`]. If dynamic registration is
48//! not available, the homeserver should document how to obtain a client ID. The
49//! client ID can then be provided with [`OAuth::restore_registered_client()`].
50//!
51//! # Login
52//!
53//! Currently, two login methods are supported by this API.
54//!
55//! ## Login with the Authorization Code flow
56//!
57//! The use of the Authorization Code flow is defined in [MSC2964] and [RFC
58//! 6749][rfc6749-auth-code].
59//!
60//! This method requires to open a URL in the end-user's browser where
61//! they will be able to log into their account in the server's web UI and grant
62//! access to their Matrix account.
63//!
64//! [`OAuth::login()`] constructs an [`OAuthAuthCodeUrlBuilder`] that can be
65//! configured, and then calling [`OAuthAuthCodeUrlBuilder::build()`] will
66//! provide the URL to present to the user in a web browser.
67//!
68//! After authenticating with the server, the user will be redirected to the
69//! provided redirect URI, with a code in the query that will allow to finish
70//! the login process by calling [`OAuth::finish_login()`].
71//!
72//! If the login needs to be cancelled before its completion,
73//! [`OAuth::abort_login()`] should be called to clean up the local data.
74//!
75//! ## Login by scanning a QR Code
76//!
77//! Logging in via a QR code is defined in [MSC4108]. It uses the Device
78//! authorization flow specified in [RFC 8628].
79//!
80//! This method requires to have another logged-in Matrix device that can
81//! display a QR Code.
82//!
83//! This login method is only available if the `e2e-encryption` cargo feature is
84//! enabled. It is not available on WASM.
85//!
86//! After scanning the QR Code, [`OAuth::login_with_qr_code()`] can be called
87//! with the QR Code's data. Then the different steps of the process need to be
88//! followed with [`LoginWithQrCode::subscribe_to_progress()`].
89//!
90//! A successful login using this method will automatically mark the device as
91//! verified and transfer all end-to-end encryption related secrets, like the
92//! private cross-signing keys and the backup key from the existing device to
93//! the new device.
94//!
95//! # Persisting/restoring a session
96//!
97//! The full session to persist can be obtained with [`OAuth::full_session()`].
98//! The different parts can also be retrieved with [`Client::session_meta()`],
99//! [`Client::session_tokens()`] and [`OAuth::client_id()`].
100//!
101//! To restore a previous session, use [`OAuth::restore_session()`].
102//!
103//! # Refresh tokens
104//!
105//! The use of refresh tokens with OAuth 2.0 servers is more common than in the
106//! Matrix specification. For this reason, it is recommended to configure the
107//! client with [`ClientBuilder::handle_refresh_tokens()`], to handle refreshing
108//! tokens automatically.
109//!
110//! Applications should then listen to session tokens changes after logging in
111//! with [`Client::subscribe_to_session_changes()`] to persist them on every
112//! change. If they are not persisted properly, the end-user will need to login
113//! again.
114//!
115//! # Unknown token error
116//!
117//! A request to the Matrix API can return an [`Error`] with an
118//! [`ErrorKind::UnknownToken`].
119//!
120//! The first step is to try to refresh the token with
121//! [`OAuth::refresh_access_token()`]. This step is done automatically if the
122//! client was built with [`ClientBuilder::handle_refresh_tokens()`].
123//!
124//! If refreshing the access token fails, the next step is to try to request a
125//! new login authorization with [`OAuth::login()`], using the device ID from
126//! the session.
127//!
128//! If this fails again, the client should assume to be logged out, and all
129//! local data should be erased.
130//!
131//! # Account management.
132//!
133//! The server might advertise a URL that allows the user to manage their
134//! account. It can be used to replace most of the Matrix APIs requiring
135//! User-Interactive Authentication.
136//!
137//! An [`AccountManagementUrlBuilder`] can be obtained with
138//! [`OAuth::account_management_url()`]. Then the action that the user wants to
139//! perform can be customized with [`AccountManagementUrlBuilder::action()`].
140//! Finally you can obtain the final URL to present to the user with
141//! [`AccountManagementUrlBuilder::build()`].
142//!
143//! # Logout
144//!
145//! To log the [`Client`] out of the session, simply call [`OAuth::logout()`].
146//!
147//! # Examples
148//!
149//! Most methods have examples, there is also an example CLI application that
150//! supports all the actions described here, in [`examples/oauth_cli`].
151//!
152//! [MSC3861]: https://github.com/matrix-org/matrix-spec-proposals/pull/3861
153//! [areweoidcyet.com]: https://areweoidcyet.com/
154//! [MSC2964]: https://github.com/matrix-org/matrix-spec-proposals/pull/2964
155//! [rfc6749-auth-code]: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1
156//! [MSC4108]: https://github.com/matrix-org/matrix-spec-proposals/pull/4108
157//! [RFC 8628]: https://datatracker.ietf.org/doc/html/rfc8628
158//! [`ClientBuilder::handle_refresh_tokens()`]: crate::ClientBuilder::handle_refresh_tokens()
159//! [`Error`]: ruma::api::client::error::Error
160//! [`ErrorKind::UnknownToken`]: ruma::api::client::error::ErrorKind::UnknownToken
161//! [`examples/oauth_cli`]: https://github.com/matrix-org/matrix-rust-sdk/tree/main/examples/oauth_cli
162
163use std::{
164    borrow::Cow,
165    collections::{BTreeSet, HashMap},
166    fmt,
167    sync::Arc,
168};
169
170use as_variant::as_variant;
171#[cfg(feature = "e2e-encryption")]
172use error::CrossProcessRefreshLockError;
173use error::{
174    OAuthAuthorizationCodeError, OAuthClientRegistrationError, OAuthDiscoveryError,
175    OAuthTokenRevocationError, RedirectUriQueryParseError,
176};
177#[cfg(feature = "e2e-encryption")]
178use matrix_sdk_base::crypto::types::qr_login::QrCodeData;
179#[cfg(feature = "e2e-encryption")]
180use matrix_sdk_base::once_cell::sync::OnceCell;
181use matrix_sdk_base::{SessionMeta, store::RoomLoadSettings};
182use oauth2::{
183    AccessToken, PkceCodeVerifier, RedirectUrl, RefreshToken, RevocationUrl, Scope,
184    StandardErrorResponse, StandardRevocableToken, TokenResponse, TokenUrl,
185    basic::BasicClient as OAuthClient,
186};
187pub use oauth2::{ClientId, CsrfToken};
188use ruma::{
189    DeviceId, OwnedDeviceId,
190    api::client::discovery::get_authorization_server_metadata::{
191        self,
192        v1::{AccountManagementAction, AuthorizationServerMetadata},
193    },
194    serde::Raw,
195};
196use serde::{Deserialize, Serialize};
197use sha2::Digest as _;
198use tokio::sync::Mutex;
199use tracing::{debug, error, instrument, trace, warn};
200use url::Url;
201
202mod account_management_url;
203mod auth_code_builder;
204#[cfg(feature = "e2e-encryption")]
205mod cross_process;
206pub mod error;
207mod http_client;
208#[cfg(feature = "e2e-encryption")]
209pub mod qrcode;
210pub mod registration;
211#[cfg(all(test, not(target_family = "wasm")))]
212mod tests;
213
214#[cfg(feature = "e2e-encryption")]
215use self::cross_process::{CrossProcessRefreshLockGuard, CrossProcessRefreshManager};
216#[cfg(feature = "e2e-encryption")]
217use self::qrcode::LoginWithQrCode;
218pub use self::{
219    account_management_url::{AccountManagementActionFull, AccountManagementUrlBuilder},
220    auth_code_builder::{OAuthAuthCodeUrlBuilder, OAuthAuthorizationData},
221    error::OAuthError,
222};
223use self::{
224    http_client::OAuthHttpClient,
225    registration::{ClientMetadata, ClientRegistrationResponse, register_client},
226};
227use super::{AuthData, SessionTokens};
228use crate::{Client, HttpError, RefreshTokenError, Result, client::SessionChange, executor::spawn};
229
230pub(crate) struct OAuthCtx {
231    /// Lock and state when multiple processes may refresh an OAuth 2.0 session.
232    #[cfg(feature = "e2e-encryption")]
233    cross_process_token_refresh_manager: OnceCell<CrossProcessRefreshManager>,
234
235    /// Deferred cross-process lock initializer.
236    ///
237    /// Note: only required because we're using the crypto store that might not
238    /// be present before reloading a session.
239    #[cfg(feature = "e2e-encryption")]
240    deferred_cross_process_lock_init: Mutex<Option<String>>,
241
242    /// Whether to allow HTTP issuer URLs.
243    insecure_discover: bool,
244}
245
246impl OAuthCtx {
247    pub(crate) fn new(insecure_discover: bool) -> Self {
248        Self {
249            insecure_discover,
250            #[cfg(feature = "e2e-encryption")]
251            cross_process_token_refresh_manager: Default::default(),
252            #[cfg(feature = "e2e-encryption")]
253            deferred_cross_process_lock_init: Default::default(),
254        }
255    }
256}
257
258pub(crate) struct OAuthAuthData {
259    pub(crate) client_id: ClientId,
260    /// The data necessary to validate authorization responses.
261    authorization_data: Mutex<HashMap<CsrfToken, AuthorizationValidationData>>,
262}
263
264#[cfg(not(tarpaulin_include))]
265impl fmt::Debug for OAuthAuthData {
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        f.debug_struct("OAuthAuthData").finish_non_exhaustive()
268    }
269}
270
271/// A high-level authentication API to interact with an OAuth 2.0 authorization
272/// server.
273#[derive(Debug, Clone)]
274pub struct OAuth {
275    /// The underlying Matrix API client.
276    client: Client,
277    /// The HTTP client used for making OAuth 2.0 request.
278    http_client: OAuthHttpClient,
279}
280
281impl OAuth {
282    pub(crate) fn new(client: Client) -> Self {
283        let http_client = OAuthHttpClient {
284            inner: client.inner.http_client.inner.clone(),
285            #[cfg(test)]
286            insecure_rewrite_https_to_http: false,
287        };
288        Self { client, http_client }
289    }
290
291    /// Rewrite HTTPS requests to use HTTP instead.
292    ///
293    /// This is a workaround to bypass some checks that require an HTTPS URL,
294    /// but we can only mock HTTP URLs.
295    #[cfg(test)]
296    pub(crate) fn insecure_rewrite_https_to_http(mut self) -> Self {
297        self.http_client.insecure_rewrite_https_to_http = true;
298        self
299    }
300
301    fn ctx(&self) -> &OAuthCtx {
302        &self.client.auth_ctx().oauth
303    }
304
305    fn http_client(&self) -> &OAuthHttpClient {
306        &self.http_client
307    }
308
309    /// Enable a cross-process store lock on the state store, to coordinate
310    /// refreshes across different processes.
311    #[cfg(feature = "e2e-encryption")]
312    pub async fn enable_cross_process_refresh_lock(
313        &self,
314        lock_value: String,
315    ) -> Result<(), OAuthError> {
316        // FIXME: it must be deferred only because we're using the crypto store and it's
317        // initialized only in `set_or_reload_session`, not if we use a dedicated store.
318        let mut lock = self.ctx().deferred_cross_process_lock_init.lock().await;
319        if lock.is_some() {
320            return Err(CrossProcessRefreshLockError::DuplicatedLock.into());
321        }
322        *lock = Some(lock_value);
323
324        Ok(())
325    }
326
327    /// Performs a deferred cross-process refresh-lock, if needs be, after an
328    /// olm machine has been initialized.
329    ///
330    /// Must be called after [`BaseClient::set_or_reload_session`].
331    #[cfg(feature = "e2e-encryption")]
332    async fn deferred_enable_cross_process_refresh_lock(&self) {
333        let deferred_init_lock = self.ctx().deferred_cross_process_lock_init.lock().await;
334
335        // Don't `take()` the value, so that subsequent calls to
336        // `enable_cross_process_refresh_lock` will keep on failing if we've enabled the
337        // lock at least once.
338        let Some(lock_value) = deferred_init_lock.as_ref() else {
339            return;
340        };
341
342        // FIXME: We shouldn't be using the crypto store for that! see also https://github.com/matrix-org/matrix-rust-sdk/issues/2472
343        let olm_machine_lock = self.client.olm_machine().await;
344        let olm_machine =
345            olm_machine_lock.as_ref().expect("there has to be an olm machine, hopefully?");
346        let store = olm_machine.store();
347        let lock =
348            store.create_store_lock("oidc_session_refresh_lock".to_owned(), lock_value.clone());
349
350        let manager = CrossProcessRefreshManager::new(store.clone(), lock);
351
352        // This method is guarded with the `deferred_cross_process_lock_init` lock held,
353        // so this `set` can't be an error.
354        let _ = self.ctx().cross_process_token_refresh_manager.set(manager);
355    }
356
357    /// The OAuth 2.0 authentication data.
358    ///
359    /// Returns `None` if the client was not registered or if the registration
360    /// was not restored with [`OAuth::restore_registered_client()`] or
361    /// [`OAuth::restore_session()`].
362    fn data(&self) -> Option<&OAuthAuthData> {
363        let data = self.client.auth_ctx().auth_data.get()?;
364        as_variant!(data, AuthData::OAuth)
365    }
366
367    /// Log in using a QR code.
368    ///
369    /// This method allows you to log in with a QR code, the existing device
370    /// needs to display the QR code which this device can scan and call
371    /// this method to log in.
372    ///
373    /// A successful login using this method will automatically mark the device
374    /// as verified and transfer all end-to-end encryption related secrets, like
375    /// the private cross-signing keys and the backup key from the existing
376    /// device to the new device.
377    ///
378    /// # Arguments
379    ///
380    /// * `data` - The data scanned from a QR code.
381    ///
382    /// * `registration_data` - The data to restore or register the client with
383    ///   the server. If this is not provided, an error will occur unless
384    ///   [`OAuth::register_client()`] or [`OAuth::restore_registered_client()`]
385    ///   was called previously.
386    ///
387    /// # Example
388    ///
389    /// ```no_run
390    /// use anyhow::bail;
391    /// use futures_util::StreamExt;
392    /// use matrix_sdk::{
393    ///     authentication::oauth::{
394    ///         registration::ClientMetadata,
395    ///         qrcode::{LoginProgress, QrCodeData, QrCodeModeData},
396    ///     },
397    ///     ruma::serde::Raw,
398    ///     Client,
399    /// };
400    /// # fn client_metadata() -> Raw<ClientMetadata> { unimplemented!() }
401    /// # _ = async {
402    /// # let bytes = unimplemented!();
403    /// // You'll need to use a different library to scan and extract the raw bytes from the QR
404    /// // code.
405    /// let qr_code_data = QrCodeData::from_bytes(bytes)?;
406    ///
407    /// // Fetch the homeserver out of the parsed QR code data.
408    /// let QrCodeModeData::Reciprocate{ server_name } = qr_code_data.mode_data else {
409    ///     bail!("The QR code is invalid, we did not receive a homeserver in the QR code.");
410    /// };
411    ///
412    /// // Build the client as usual.
413    /// let client = Client::builder()
414    ///     .server_name_or_homeserver_url(server_name)
415    ///     .handle_refresh_tokens()
416    ///     .build()
417    ///     .await?;
418    ///
419    /// let oauth = client.oauth();
420    /// let client_metadata: Raw<ClientMetadata> = client_metadata();
421    /// let registration_data = client_metadata.into();
422    ///
423    /// // Subscribing to the progress is necessary since we need to input the check
424    /// // code on the existing device.
425    /// let login = oauth.login_with_qr_code(&qr_code_data, Some(&registration_data));
426    /// let mut progress = login.subscribe_to_progress();
427    ///
428    /// // Create a task which will show us the progress and tell us the check
429    /// // code to input in the existing device.
430    /// let task = tokio::spawn(async move {
431    ///     while let Some(state) = progress.next().await {
432    ///         match state {
433    ///             LoginProgress::Starting => (),
434    ///             LoginProgress::EstablishingSecureChannel { check_code } => {
435    ///                 let code = check_code.to_digit();
436    ///                 println!("Please enter the following code into the other device {code:02}");
437    ///             },
438    ///             LoginProgress::WaitingForToken { user_code } => {
439    ///                 println!("Please use your other device to confirm the log in {user_code}")
440    ///             },
441    ///             LoginProgress::Done => break,
442    ///         }
443    ///     }
444    /// });
445    ///
446    /// // Now run the future to complete the login.
447    /// login.await?;
448    /// task.abort();
449    ///
450    /// println!("Successfully logged in: {:?} {:?}", client.user_id(), client.device_id());
451    /// # anyhow::Ok(()) };
452    /// ```
453    #[cfg(feature = "e2e-encryption")]
454    pub fn login_with_qr_code<'a>(
455        &'a self,
456        data: &'a QrCodeData,
457        registration_data: Option<&'a ClientRegistrationData>,
458    ) -> LoginWithQrCode<'a> {
459        LoginWithQrCode::new(&self.client, data, registration_data)
460    }
461
462    /// Restore or register the OAuth 2.0 client for the server with the given
463    /// metadata, with the given optional [`ClientRegistrationData`].
464    ///
465    /// If we already have a client ID, this is a noop.
466    ///
467    /// Returns an error if there was a problem using the registration method.
468    async fn use_registration_data(
469        &self,
470        server_metadata: &AuthorizationServerMetadata,
471        data: Option<&ClientRegistrationData>,
472    ) -> std::result::Result<(), OAuthError> {
473        if self.client_id().is_some() {
474            tracing::info!("OAuth 2.0 is already configured.");
475            return Ok(());
476        }
477
478        let Some(data) = data else {
479            return Err(OAuthError::NotRegistered);
480        };
481
482        if let Some(static_registrations) = &data.static_registrations {
483            let client_id = static_registrations
484                .get(&self.client.homeserver())
485                .or_else(|| static_registrations.get(&server_metadata.issuer));
486
487            if let Some(client_id) = client_id {
488                self.restore_registered_client(client_id.clone());
489                return Ok(());
490            }
491        }
492
493        self.register_client_inner(server_metadata, &data.metadata).await?;
494
495        Ok(())
496    }
497
498    /// The account management actions supported by the authorization server's
499    /// account management URL.
500    ///
501    /// Returns an error if the request to get the server metadata fails.
502    pub async fn account_management_actions_supported(
503        &self,
504    ) -> Result<BTreeSet<AccountManagementAction>, OAuthError> {
505        let server_metadata = self.server_metadata().await?;
506
507        Ok(server_metadata.account_management_actions_supported)
508    }
509
510    /// Get the account management URL where the user can manage their
511    /// identity-related settings.
512    ///
513    /// This will always request the latest server metadata to get the account
514    /// management URL.
515    ///
516    /// To avoid making a request each time, you can use
517    /// [`OAuth::account_management_url()`].
518    ///
519    /// Returns an [`AccountManagementUrlBuilder`] if the URL was found. An
520    /// optional action to perform can be added with `.action()`, and the final
521    /// URL is obtained with `.build()`.
522    ///
523    /// Returns `Ok(None)` if the URL was not found.
524    ///
525    /// Returns an error if the request to get the server metadata fails or the
526    /// URL could not be parsed.
527    pub async fn fetch_account_management_url(
528        &self,
529    ) -> Result<Option<AccountManagementUrlBuilder>, OAuthError> {
530        let server_metadata = self.server_metadata().await?;
531        Ok(server_metadata.account_management_uri.map(AccountManagementUrlBuilder::new))
532    }
533
534    /// Get the account management URL where the user can manage their
535    /// identity-related settings.
536    ///
537    /// This method will cache the URL for a while, if the cache is not
538    /// populated it will request the server metadata, like a call to
539    /// [`OAuth::fetch_account_management_url()`], and cache the resulting URL
540    /// before returning it.
541    ///
542    /// Returns an [`AccountManagementUrlBuilder`] if the URL was found. An
543    /// optional action to perform can be added with `.action()`, and the final
544    /// URL is obtained with `.build()`.
545    ///
546    /// Returns `Ok(None)` if the URL was not found.
547    ///
548    /// Returns an error if the request to get the server metadata fails or the
549    /// URL could not be parsed.
550    pub async fn account_management_url(
551        &self,
552    ) -> Result<Option<AccountManagementUrlBuilder>, OAuthError> {
553        const CACHE_KEY: &str = "SERVER_METADATA";
554
555        let mut cache = self.client.inner.caches.server_metadata.lock().await;
556
557        let metadata = if let Some(metadata) = cache.get(CACHE_KEY) {
558            metadata
559        } else {
560            let server_metadata = self.server_metadata().await?;
561            cache.insert(CACHE_KEY.to_owned(), server_metadata.clone());
562            server_metadata
563        };
564
565        Ok(metadata.account_management_uri.map(AccountManagementUrlBuilder::new))
566    }
567
568    /// Fetch the OAuth 2.0 authorization server metadata of the homeserver.
569    ///
570    /// Returns an error if a problem occurred when fetching or validating the
571    /// metadata.
572    pub async fn server_metadata(
573        &self,
574    ) -> Result<AuthorizationServerMetadata, OAuthDiscoveryError> {
575        let is_endpoint_unsupported = |error: &HttpError| {
576            error
577                .as_client_api_error()
578                .is_some_and(|err| err.status_code == http::StatusCode::NOT_FOUND)
579        };
580
581        let response =
582            self.client.send(get_authorization_server_metadata::v1::Request::new()).await.map_err(
583                |error| {
584                    // If the endpoint returns a 404, i.e. the server doesn't support the endpoint.
585                    if is_endpoint_unsupported(&error) {
586                        OAuthDiscoveryError::NotSupported
587                    } else {
588                        error.into()
589                    }
590                },
591            )?;
592
593        let metadata = response.metadata.deserialize()?;
594
595        if self.ctx().insecure_discover {
596            metadata.insecure_validate_urls()?;
597        } else {
598            metadata.validate_urls()?;
599        }
600
601        Ok(metadata)
602    }
603
604    /// The OAuth 2.0 unique identifier of this client obtained after
605    /// registration.
606    ///
607    /// Returns `None` if the client was not registered or if the registration
608    /// was not restored with [`OAuth::restore_registered_client()`] or
609    /// [`OAuth::restore_session()`].
610    pub fn client_id(&self) -> Option<&ClientId> {
611        self.data().map(|data| &data.client_id)
612    }
613
614    /// The OAuth 2.0 user session of this client.
615    ///
616    /// Returns `None` if the client was not logged in.
617    pub fn user_session(&self) -> Option<UserSession> {
618        let meta = self.client.session_meta()?.to_owned();
619        let tokens = self.client.session_tokens()?;
620        Some(UserSession { meta, tokens })
621    }
622
623    /// The full OAuth 2.0 session of this client.
624    ///
625    /// Returns `None` if the client was not logged in with the OAuth 2.0 API.
626    pub fn full_session(&self) -> Option<OAuthSession> {
627        let user = self.user_session()?;
628        let data = self.data()?;
629        Some(OAuthSession { client_id: data.client_id.clone(), user })
630    }
631
632    /// Register a client with the OAuth 2.0 server.
633    ///
634    /// This should be called before any authorization request with an
635    /// authorization server that supports dynamic client registration. If the
636    /// client registered with the server manually, it should use
637    /// [`OAuth::restore_registered_client()`].
638    ///
639    /// Note that this method only supports public clients, i.e. clients without
640    /// a secret.
641    ///
642    /// # Arguments
643    ///
644    /// * `client_metadata` - The serialized client metadata to register.
645    ///
646    /// # Panic
647    ///
648    /// Panics if the authentication data was already set.
649    ///
650    /// # Example
651    ///
652    /// ```no_run
653    /// use matrix_sdk::{Client, ServerName};
654    /// # use matrix_sdk::authentication::oauth::ClientId;
655    /// # use matrix_sdk::authentication::oauth::registration::ClientMetadata;
656    /// # use ruma::serde::Raw;
657    /// # let client_metadata = unimplemented!();
658    /// # fn persist_client_registration (_: url::Url, _: &ClientId) {}
659    /// # _ = async {
660    /// let server_name = ServerName::parse("myhomeserver.org")?;
661    /// let client = Client::builder().server_name(&server_name).build().await?;
662    /// let oauth = client.oauth();
663    ///
664    /// if let Err(error) = oauth.server_metadata().await {
665    ///     if error.is_not_supported() {
666    ///         println!("OAuth 2.0 is not supported");
667    ///     }
668    ///
669    ///     return Err(error.into());
670    /// }
671    ///
672    /// let response = oauth
673    ///     .register_client(&client_metadata)
674    ///     .await?;
675    ///
676    /// println!(
677    ///     "Registered with client_id: {}",
678    ///     response.client_id.as_str()
679    /// );
680    ///
681    /// // The API only supports clients without secrets.
682    /// let client_id = response.client_id;
683    ///
684    /// persist_client_registration(client.homeserver(), &client_id);
685    /// # anyhow::Ok(()) };
686    /// ```
687    pub async fn register_client(
688        &self,
689        client_metadata: &Raw<ClientMetadata>,
690    ) -> Result<ClientRegistrationResponse, OAuthError> {
691        let server_metadata = self.server_metadata().await?;
692        Ok(self.register_client_inner(&server_metadata, client_metadata).await?)
693    }
694
695    async fn register_client_inner(
696        &self,
697        server_metadata: &AuthorizationServerMetadata,
698        client_metadata: &Raw<ClientMetadata>,
699    ) -> Result<ClientRegistrationResponse, OAuthClientRegistrationError> {
700        let registration_endpoint = server_metadata
701            .registration_endpoint
702            .as_ref()
703            .ok_or(OAuthClientRegistrationError::NotSupported)?;
704
705        let registration_response =
706            register_client(self.http_client(), registration_endpoint, client_metadata).await?;
707
708        // The format of the credentials changes according to the client metadata that
709        // was sent. Public clients only get a client ID.
710        self.restore_registered_client(registration_response.client_id.clone());
711
712        Ok(registration_response)
713    }
714
715    /// Set the data of a client that is registered with an OAuth 2.0
716    /// authorization server.
717    ///
718    /// This should be called when logging in with a server that is already
719    /// known by the client.
720    ///
721    /// Note that this method only supports public clients, i.e. clients with
722    /// no credentials.
723    ///
724    /// # Arguments
725    ///
726    /// * `client_id` - The unique identifier to authenticate the client with
727    ///   the server, obtained after registration.
728    ///
729    /// # Panic
730    ///
731    /// Panics if authentication data was already set.
732    pub fn restore_registered_client(&self, client_id: ClientId) {
733        let data = OAuthAuthData { client_id, authorization_data: Default::default() };
734
735        self.client
736            .auth_ctx()
737            .auth_data
738            .set(AuthData::OAuth(data))
739            .expect("Client authentication data was already set");
740    }
741
742    /// Restore a previously logged in session.
743    ///
744    /// This can be used to restore the client to a logged in state, including
745    /// loading the sync state and the encryption keys from the store, if
746    /// one was set up.
747    ///
748    /// # Arguments
749    ///
750    /// * `session` - The session to restore.
751    /// * `room_load_settings` — Specify how many rooms must be restored; use
752    ///   `::default()` if you don't know which value to pick.
753    ///
754    /// # Panic
755    ///
756    /// Panics if authentication data was already set.
757    pub async fn restore_session(
758        &self,
759        session: OAuthSession,
760        room_load_settings: RoomLoadSettings,
761    ) -> Result<()> {
762        let OAuthSession { client_id, user: UserSession { meta, tokens } } = session;
763
764        let data = OAuthAuthData { client_id, authorization_data: Default::default() };
765
766        self.client.auth_ctx().set_session_tokens(tokens.clone());
767        self.client
768            .base_client()
769            .activate(
770                meta,
771                room_load_settings,
772                #[cfg(feature = "e2e-encryption")]
773                None,
774            )
775            .await?;
776        #[cfg(feature = "e2e-encryption")]
777        self.deferred_enable_cross_process_refresh_lock().await;
778
779        self.client
780            .inner
781            .auth_ctx
782            .auth_data
783            .set(AuthData::OAuth(data))
784            .expect("Client authentication data was already set");
785
786        // Initialize the cross-process locking by saving our tokens' hash into the
787        // database, if we've enabled the cross-process lock.
788
789        #[cfg(feature = "e2e-encryption")]
790        if let Some(cross_process_lock) = self.ctx().cross_process_token_refresh_manager.get() {
791            cross_process_lock.restore_session(&tokens).await;
792
793            let mut guard = cross_process_lock
794                .spin_lock()
795                .await
796                .map_err(|err| crate::Error::OAuth(Box::new(err.into())))?;
797
798            // After we got the lock, it's possible that our session doesn't match the one
799            // read from the database, because of a race: another process has
800            // refreshed the tokens while we were waiting for the lock.
801            //
802            // In that case, if there's a mismatch, we reload the session and update the
803            // hash. Otherwise, we save our hash into the database.
804
805            if guard.hash_mismatch {
806                Box::pin(self.handle_session_hash_mismatch(&mut guard))
807                    .await
808                    .map_err(|err| crate::Error::OAuth(Box::new(err.into())))?;
809            } else {
810                guard
811                    .save_in_memory_and_db(&tokens)
812                    .await
813                    .map_err(|err| crate::Error::OAuth(Box::new(err.into())))?;
814                // No need to call the save_session_callback here; it was the
815                // source of the session, so it's already in
816                // sync with what we had.
817            }
818        }
819
820        #[cfg(feature = "e2e-encryption")]
821        self.client.encryption().spawn_initialization_task(None).await;
822
823        Ok(())
824    }
825
826    #[cfg(feature = "e2e-encryption")]
827    async fn handle_session_hash_mismatch(
828        &self,
829        guard: &mut CrossProcessRefreshLockGuard,
830    ) -> Result<(), CrossProcessRefreshLockError> {
831        trace!("Handling hash mismatch.");
832
833        let callback = self
834            .client
835            .auth_ctx()
836            .reload_session_callback
837            .get()
838            .ok_or(CrossProcessRefreshLockError::MissingReloadSession)?;
839
840        match callback(self.client.clone()) {
841            Ok(tokens) => {
842                guard.handle_mismatch(&tokens).await?;
843
844                self.client.auth_ctx().set_session_tokens(tokens.clone());
845                // The app's callback acted as authoritative here, so we're not
846                // saving the data back into the app, as that would have no
847                // effect.
848            }
849            Err(err) => {
850                error!("when reloading OAuth 2.0 session tokens from callback: {err}");
851            }
852        }
853
854        Ok(())
855    }
856
857    /// The scopes to request for logging in and the corresponding device ID.
858    fn login_scopes(
859        device_id: Option<OwnedDeviceId>,
860        additional_scopes: Option<Vec<Scope>>,
861    ) -> (Vec<Scope>, OwnedDeviceId) {
862        /// Scope to grand full access to the client-server API.
863        const SCOPE_MATRIX_CLIENT_SERVER_API_FULL_ACCESS: &str =
864            "urn:matrix:org.matrix.msc2967.client:api:*";
865        /// Prefix of the scope to bind a device ID to an access token.
866        const SCOPE_MATRIX_DEVICE_ID_PREFIX: &str = "urn:matrix:org.matrix.msc2967.client:device:";
867
868        // Generate the device ID if it is not provided.
869        let device_id = device_id.unwrap_or_else(DeviceId::new);
870
871        let mut scopes = vec![
872            Scope::new(SCOPE_MATRIX_CLIENT_SERVER_API_FULL_ACCESS.to_owned()),
873            Scope::new(format!("{SCOPE_MATRIX_DEVICE_ID_PREFIX}{device_id}")),
874        ];
875
876        if let Some(extra_scopes) = additional_scopes {
877            scopes.extend(extra_scopes);
878        }
879
880        (scopes, device_id)
881    }
882
883    /// Log in via OAuth 2.0 with the Authorization Code flow.
884    ///
885    /// This method requires to open a URL in the end-user's browser where they
886    /// will be able to log into their account in the server's web UI and grant
887    /// access to their Matrix account.
888    ///
889    /// The [`OAuthAuthCodeUrlBuilder`] that is returned allows to customize a
890    /// few settings before calling `.build()` to obtain the URL to open in the
891    /// browser of the end-user.
892    ///
893    /// [`OAuth::finish_login()`] must be called once the user has been
894    /// redirected to the `redirect_uri`. [`OAuth::abort_login()`] should be
895    /// called instead if the authorization should be aborted before completion.
896    ///
897    /// # Arguments
898    ///
899    /// * `redirect_uri` - The URI where the end user will be redirected after
900    ///   authorizing the login. It must be one of the redirect URIs sent in the
901    ///   client metadata during registration.
902    ///
903    /// * `device_id` - The unique ID that will be associated with the session.
904    ///   If not set, a random one will be generated. It can be an existing
905    ///   device ID from a previous login call. Note that this should be done
906    ///   only if the client also holds the corresponding encryption keys.
907    ///
908    /// * `registration_data` - The data to restore or register the client with
909    ///   the server. If this is not provided, an error will occur unless
910    ///   [`OAuth::register_client()`] or [`OAuth::restore_registered_client()`]
911    ///   was called previously.
912    ///
913    /// * `additional_scopes` - Additional scopes to request from the
914    ///   authorization server, e.g. "urn:matrix:client:com.example.msc9999.foo".
915    ///   The scopes for API access and the device ID according to the
916    ///   [specification](https://spec.matrix.org/v1.15/client-server-api/#allocated-scope-tokens)
917    ///   are always requested.
918    ///
919    /// # Example
920    ///
921    /// ```no_run
922    /// use matrix_sdk::{
923    ///     authentication::oauth::registration::ClientMetadata,
924    ///     ruma::serde::Raw,
925    /// };
926    /// use url::Url;
927    /// # use matrix_sdk::Client;
928    /// # let client: Client = unimplemented!();
929    /// # let redirect_uri = unimplemented!();
930    /// # async fn open_uri_and_wait_for_redirect(uri: Url) -> Url { unimplemented!() };
931    /// # fn client_metadata() -> Raw<ClientMetadata> { unimplemented!() };
932    /// # _ = async {
933    /// let oauth = client.oauth();
934    /// let client_metadata: Raw<ClientMetadata> = client_metadata();
935    /// let registration_data = client_metadata.into();
936    ///
937    /// let auth_data = oauth.login(redirect_uri, None, Some(registration_data), None)
938    ///                      .build()
939    ///                      .await?;
940    ///
941    /// // Open auth_data.url and wait for response at the redirect URI.
942    /// let redirected_to_uri: Url = open_uri_and_wait_for_redirect(auth_data.url).await;
943    ///
944    /// oauth.finish_login(redirected_to_uri.into()).await?;
945    ///
946    /// // The session tokens can be persisted from the
947    /// // `OAuth::full_session()` method.
948    ///
949    /// // You can now make requests to the Matrix API.
950    /// let _me = client.whoami().await?;
951    /// # anyhow::Ok(()) }
952    /// ```
953    pub fn login(
954        &self,
955        redirect_uri: Url,
956        device_id: Option<OwnedDeviceId>,
957        registration_data: Option<ClientRegistrationData>,
958        additional_scopes: Option<Vec<Scope>>,
959    ) -> OAuthAuthCodeUrlBuilder {
960        let (scopes, device_id) = Self::login_scopes(device_id, additional_scopes);
961
962        OAuthAuthCodeUrlBuilder::new(
963            self.clone(),
964            scopes.to_vec(),
965            device_id,
966            redirect_uri,
967            registration_data,
968        )
969    }
970
971    /// Finish the login process.
972    ///
973    /// This method should be called after the URL returned by
974    /// [`OAuthAuthCodeUrlBuilder::build()`] has been presented and the user has
975    /// been redirected to the redirect URI after completing the authorization.
976    ///
977    /// If the authorization needs to be cancelled before its completion,
978    /// [`OAuth::abort_login()`] should be used instead to clean up the local
979    /// data.
980    ///
981    /// # Arguments
982    ///
983    /// * `url_or_query` - The URI where the user was redirected, or just its
984    ///   query part.
985    ///
986    /// Returns an error if the authorization failed, if a request fails, or if
987    /// the client was already logged in with a different session.
988    pub async fn finish_login(&self, url_or_query: UrlOrQuery) -> Result<()> {
989        let response = AuthorizationResponse::parse_url_or_query(&url_or_query)
990            .map_err(|error| OAuthError::from(OAuthAuthorizationCodeError::from(error)))?;
991
992        let auth_code = match response {
993            AuthorizationResponse::Success(code) => code,
994            AuthorizationResponse::Error(error) => {
995                self.abort_login(&error.state).await;
996                return Err(OAuthError::from(OAuthAuthorizationCodeError::from(error.error)).into());
997            }
998        };
999
1000        let device_id = self.finish_authorization(auth_code).await?;
1001        self.load_session(device_id).await
1002    }
1003
1004    /// Load the session after login.
1005    ///
1006    /// Returns an error if the request to get the user ID fails, or if the
1007    /// client was already logged in with a different session.
1008    pub(crate) async fn load_session(&self, device_id: OwnedDeviceId) -> Result<()> {
1009        // Get the user ID.
1010        let whoami_res = self.client.whoami().await.map_err(crate::Error::from)?;
1011
1012        let new_session = SessionMeta { user_id: whoami_res.user_id, device_id };
1013
1014        if let Some(current_session) = self.client.session_meta() {
1015            if new_session != *current_session {
1016                return Err(OAuthError::SessionMismatch.into());
1017            }
1018        } else {
1019            self.client
1020                .base_client()
1021                .activate(
1022                    new_session,
1023                    RoomLoadSettings::default(),
1024                    #[cfg(feature = "e2e-encryption")]
1025                    None,
1026                )
1027                .await?;
1028            // At this point the Olm machine has been set up.
1029
1030            // Enable the cross-process lock for refreshes, if needs be.
1031            #[cfg(feature = "e2e-encryption")]
1032            self.enable_cross_process_lock().await.map_err(OAuthError::from)?;
1033
1034            #[cfg(feature = "e2e-encryption")]
1035            self.client.encryption().spawn_initialization_task(None).await;
1036        }
1037
1038        Ok(())
1039    }
1040
1041    #[cfg(feature = "e2e-encryption")]
1042    pub(crate) async fn enable_cross_process_lock(
1043        &self,
1044    ) -> Result<(), CrossProcessRefreshLockError> {
1045        // Enable the cross-process lock for refreshes, if needs be.
1046        self.deferred_enable_cross_process_refresh_lock().await;
1047
1048        if let Some(cross_process_manager) = self.ctx().cross_process_token_refresh_manager.get()
1049            && let Some(tokens) = self.client.session_tokens()
1050        {
1051            let mut cross_process_guard = cross_process_manager.spin_lock().await?;
1052
1053            if cross_process_guard.hash_mismatch {
1054                // At this point, we're finishing a login while another process had written
1055                // something in the database. It's likely the information in the database is
1056                // just outdated and wasn't properly updated, but display a warning, just in
1057                // case this happens frequently.
1058                warn!("unexpected cross-process hash mismatch when finishing login (see comment)");
1059            }
1060
1061            cross_process_guard.save_in_memory_and_db(&tokens).await?;
1062        }
1063
1064        Ok(())
1065    }
1066
1067    /// Finish the authorization process.
1068    ///
1069    /// This method should be called after the URL returned by
1070    /// [`OAuthAuthCodeUrlBuilder::build()`] has been presented and the user has
1071    /// been redirected to the redirect URI after a successful authorization.
1072    ///
1073    /// # Arguments
1074    ///
1075    /// * `auth_code` - The response received as part of the redirect URI when
1076    ///   the authorization was successful.
1077    ///
1078    /// Returns the device ID used in the authorized scope if it succeeds.
1079    /// Returns an error if a request fails.
1080    async fn finish_authorization(
1081        &self,
1082        auth_code: AuthorizationCode,
1083    ) -> Result<OwnedDeviceId, OAuthError> {
1084        let data = self.data().ok_or(OAuthError::NotAuthenticated)?;
1085        let client_id = data.client_id.clone();
1086
1087        let validation_data = data
1088            .authorization_data
1089            .lock()
1090            .await
1091            .remove(&auth_code.state)
1092            .ok_or(OAuthAuthorizationCodeError::InvalidState)?;
1093
1094        let token_uri = TokenUrl::from_url(validation_data.server_metadata.token_endpoint.clone());
1095
1096        let response = OAuthClient::new(client_id)
1097            .set_token_uri(token_uri)
1098            .exchange_code(oauth2::AuthorizationCode::new(auth_code.code))
1099            .set_pkce_verifier(validation_data.pkce_verifier)
1100            .set_redirect_uri(Cow::Owned(validation_data.redirect_uri))
1101            .request_async(self.http_client())
1102            .await
1103            .map_err(OAuthAuthorizationCodeError::RequestToken)?;
1104
1105        self.client.auth_ctx().set_session_tokens(SessionTokens {
1106            access_token: response.access_token().secret().clone(),
1107            refresh_token: response.refresh_token().map(RefreshToken::secret).cloned(),
1108        });
1109
1110        Ok(validation_data.device_id)
1111    }
1112
1113    /// Abort the login process.
1114    ///
1115    /// This method should be called if a login should be aborted before it is
1116    /// completed.
1117    ///
1118    /// If the login has been completed, [`OAuth::finish_login()`] should be
1119    /// used instead.
1120    ///
1121    /// # Arguments
1122    ///
1123    /// * `state` - The state provided in [`OAuthAuthorizationData`] after
1124    ///   building the authorization URL.
1125    pub async fn abort_login(&self, state: &CsrfToken) {
1126        if let Some(data) = self.data() {
1127            data.authorization_data.lock().await.remove(state);
1128        }
1129    }
1130
1131    /// Request codes from the authorization server for logging in with another
1132    /// device.
1133    #[cfg(feature = "e2e-encryption")]
1134    async fn request_device_authorization(
1135        &self,
1136        server_metadata: &AuthorizationServerMetadata,
1137        device_id: Option<OwnedDeviceId>,
1138    ) -> Result<oauth2::StandardDeviceAuthorizationResponse, qrcode::DeviceAuthorizationOAuthError>
1139    {
1140        let (scopes, _) = Self::login_scopes(device_id, None);
1141
1142        let client_id = self.client_id().ok_or(OAuthError::NotRegistered)?.clone();
1143
1144        let device_authorization_url = server_metadata
1145            .device_authorization_endpoint
1146            .clone()
1147            .map(oauth2::DeviceAuthorizationUrl::from_url)
1148            .ok_or(qrcode::DeviceAuthorizationOAuthError::NoDeviceAuthorizationEndpoint)?;
1149
1150        let response = OAuthClient::new(client_id)
1151            .set_device_authorization_url(device_authorization_url)
1152            .exchange_device_code()
1153            .add_scopes(scopes)
1154            .request_async(self.http_client())
1155            .await?;
1156
1157        Ok(response)
1158    }
1159
1160    /// Exchange the device code against an access token.
1161    #[cfg(feature = "e2e-encryption")]
1162    async fn exchange_device_code(
1163        &self,
1164        server_metadata: &AuthorizationServerMetadata,
1165        device_authorization_response: &oauth2::StandardDeviceAuthorizationResponse,
1166    ) -> Result<(), qrcode::DeviceAuthorizationOAuthError> {
1167        use oauth2::TokenResponse;
1168
1169        let client_id = self.client_id().ok_or(OAuthError::NotRegistered)?.clone();
1170
1171        let token_uri = TokenUrl::from_url(server_metadata.token_endpoint.clone());
1172
1173        let response = OAuthClient::new(client_id)
1174            .set_token_uri(token_uri)
1175            .exchange_device_access_token(device_authorization_response)
1176            .request_async(self.http_client(), tokio::time::sleep, None)
1177            .await?;
1178
1179        self.client.auth_ctx().set_session_tokens(SessionTokens {
1180            access_token: response.access_token().secret().to_owned(),
1181            refresh_token: response.refresh_token().map(|t| t.secret().to_owned()),
1182        });
1183
1184        Ok(())
1185    }
1186
1187    async fn refresh_access_token_inner(
1188        self,
1189        refresh_token: String,
1190        token_endpoint: Url,
1191        client_id: ClientId,
1192        #[cfg(feature = "e2e-encryption")] cross_process_lock: Option<CrossProcessRefreshLockGuard>,
1193    ) -> Result<(), OAuthError> {
1194        trace!(
1195            "Token refresh: attempting to refresh with refresh_token {:x}",
1196            hash_str(&refresh_token)
1197        );
1198
1199        let token = RefreshToken::new(refresh_token.clone());
1200        let token_uri = TokenUrl::from_url(token_endpoint);
1201
1202        let response = OAuthClient::new(client_id)
1203            .set_token_uri(token_uri)
1204            .exchange_refresh_token(&token)
1205            .request_async(self.http_client())
1206            .await
1207            .map_err(OAuthError::RefreshToken)?;
1208
1209        let new_access_token = response.access_token().secret().clone();
1210        let new_refresh_token = response.refresh_token().map(RefreshToken::secret).cloned();
1211
1212        trace!(
1213            "Token refresh: new refresh_token: {} / access_token: {:x}",
1214            new_refresh_token
1215                .as_deref()
1216                .map(|token| format!("{:x}", hash_str(token)))
1217                .unwrap_or_else(|| "<none>".to_owned()),
1218            hash_str(&new_access_token)
1219        );
1220
1221        let tokens = SessionTokens {
1222            access_token: new_access_token,
1223            refresh_token: new_refresh_token.or(Some(refresh_token)),
1224        };
1225
1226        #[cfg(feature = "e2e-encryption")]
1227        let tokens_clone = tokens.clone();
1228
1229        self.client.auth_ctx().set_session_tokens(tokens);
1230
1231        // Call the save_session_callback if set, while the optional lock is being held.
1232        if let Some(save_session_callback) = self.client.auth_ctx().save_session_callback.get() {
1233            // Satisfies the save_session_callback invariant: set_session_tokens has
1234            // been called just above.
1235            if let Err(err) = save_session_callback(self.client.clone()) {
1236                error!("when saving session after refresh: {err}");
1237            }
1238        }
1239
1240        #[cfg(feature = "e2e-encryption")]
1241        if let Some(mut lock) = cross_process_lock {
1242            lock.save_in_memory_and_db(&tokens_clone).await?;
1243        }
1244
1245        _ = self.client.auth_ctx().session_change_sender.send(SessionChange::TokensRefreshed);
1246
1247        Ok(())
1248    }
1249
1250    /// Refresh the access token.
1251    ///
1252    /// This should be called when the access token has expired. It should not
1253    /// be needed to call this manually if the [`Client`] was constructed with
1254    /// [`ClientBuilder::handle_refresh_tokens()`].
1255    ///
1256    /// This method is protected behind a lock, so calling this method several
1257    /// times at once will only call the endpoint once and all subsequent calls
1258    /// will wait for the result of the first call.
1259    ///
1260    /// [`ClientBuilder::handle_refresh_tokens()`]: crate::ClientBuilder::handle_refresh_tokens()
1261    #[instrument(skip_all)]
1262    pub async fn refresh_access_token(&self) -> Result<(), RefreshTokenError> {
1263        macro_rules! fail {
1264            ($lock:expr, $err:expr) => {
1265                let error = $err;
1266                *$lock = Err(error.clone());
1267                return Err(error);
1268            };
1269        }
1270
1271        let client = &self.client;
1272
1273        let refresh_status_lock = client.auth_ctx().refresh_token_lock.clone().try_lock_owned();
1274
1275        let Ok(mut refresh_status_guard) = refresh_status_lock else {
1276            debug!("another refresh is happening, waiting for result.");
1277            // There's already a request to refresh happening in the same process. Wait for
1278            // it to finish.
1279            let res = client.auth_ctx().refresh_token_lock.lock().await.clone();
1280            debug!("other refresh is a {}", if res.is_ok() { "success" } else { "failure " });
1281            return res;
1282        };
1283
1284        debug!("no other refresh happening in background, starting.");
1285
1286        #[cfg(feature = "e2e-encryption")]
1287        let cross_process_guard =
1288            if let Some(manager) = self.ctx().cross_process_token_refresh_manager.get() {
1289                let mut cross_process_guard = match manager
1290                    .spin_lock()
1291                    .await
1292                    .map_err(|err| RefreshTokenError::OAuth(Arc::new(err.into())))
1293                {
1294                    Ok(guard) => guard,
1295                    Err(err) => {
1296                        warn!("couldn't acquire cross-process lock (timeout)");
1297                        fail!(refresh_status_guard, err);
1298                    }
1299                };
1300
1301                if cross_process_guard.hash_mismatch {
1302                    Box::pin(self.handle_session_hash_mismatch(&mut cross_process_guard))
1303                        .await
1304                        .map_err(|err| RefreshTokenError::OAuth(Arc::new(err.into())))?;
1305                    // Optimistic exit: assume that the underlying process did update fast enough.
1306                    // In the worst case, we'll do another refresh Soon™.
1307                    tracing::info!("other process handled refresh for us, assuming success");
1308                    *refresh_status_guard = Ok(());
1309                    return Ok(());
1310                }
1311
1312                Some(cross_process_guard)
1313            } else {
1314                None
1315            };
1316
1317        let Some(session_tokens) = self.client.session_tokens() else {
1318            warn!("invalid state: missing session tokens");
1319            fail!(refresh_status_guard, RefreshTokenError::RefreshTokenRequired);
1320        };
1321
1322        let Some(refresh_token) = session_tokens.refresh_token else {
1323            warn!("invalid state: missing session tokens");
1324            fail!(refresh_status_guard, RefreshTokenError::RefreshTokenRequired);
1325        };
1326
1327        let server_metadata = match self.server_metadata().await {
1328            Ok(metadata) => metadata,
1329            Err(err) => {
1330                warn!("couldn't get authorization server metadata: {err:?}");
1331                fail!(refresh_status_guard, RefreshTokenError::OAuth(Arc::new(err.into())));
1332            }
1333        };
1334
1335        let Some(client_id) = self.client_id().cloned() else {
1336            warn!("invalid state: missing client ID");
1337            fail!(
1338                refresh_status_guard,
1339                RefreshTokenError::OAuth(Arc::new(OAuthError::NotAuthenticated))
1340            );
1341        };
1342
1343        // Do not interrupt refresh access token requests and processing, by detaching
1344        // the request sending and response processing.
1345        // Make sure to keep the `refresh_status_guard` during the entire processing.
1346
1347        let this = self.clone();
1348
1349        spawn(async move {
1350            match this
1351                .refresh_access_token_inner(
1352                    refresh_token,
1353                    server_metadata.token_endpoint,
1354                    client_id,
1355                    #[cfg(feature = "e2e-encryption")]
1356                    cross_process_guard,
1357                )
1358                .await
1359            {
1360                Ok(()) => {
1361                    debug!("success refreshing a token");
1362                    *refresh_status_guard = Ok(());
1363                    Ok(())
1364                }
1365
1366                Err(err) => {
1367                    let err = RefreshTokenError::OAuth(Arc::new(err));
1368                    warn!("error refreshing an OAuth 2.0 token: {err}");
1369                    fail!(refresh_status_guard, err);
1370                }
1371            }
1372        })
1373        .await
1374        .expect("joining")
1375    }
1376
1377    /// Log out from the currently authenticated session.
1378    pub async fn logout(&self) -> Result<(), OAuthError> {
1379        let client_id = self.client_id().ok_or(OAuthError::NotAuthenticated)?.clone();
1380
1381        let server_metadata = self.server_metadata().await?;
1382        let revocation_url = RevocationUrl::from_url(server_metadata.revocation_endpoint);
1383
1384        let tokens = self.client.session_tokens().ok_or(OAuthError::NotAuthenticated)?;
1385
1386        // Revoke the access token, it should revoke both tokens.
1387        OAuthClient::new(client_id)
1388            .set_revocation_url(revocation_url)
1389            .revoke_token(StandardRevocableToken::AccessToken(AccessToken::new(
1390                tokens.access_token,
1391            )))
1392            .map_err(OAuthTokenRevocationError::Url)?
1393            .request_async(self.http_client())
1394            .await
1395            .map_err(OAuthTokenRevocationError::Revoke)?;
1396
1397        #[cfg(feature = "e2e-encryption")]
1398        if let Some(manager) = self.ctx().cross_process_token_refresh_manager.get() {
1399            manager.on_logout().await?;
1400        }
1401
1402        Ok(())
1403    }
1404}
1405
1406/// A full session for the OAuth 2.0 API.
1407#[derive(Debug, Clone)]
1408pub struct OAuthSession {
1409    /// The client ID obtained after registration.
1410    pub client_id: ClientId,
1411
1412    /// The user session.
1413    pub user: UserSession,
1414}
1415
1416/// A user session for the OAuth 2.0 API.
1417#[derive(Debug, Clone, Serialize, Deserialize)]
1418pub struct UserSession {
1419    /// The Matrix user session info.
1420    #[serde(flatten)]
1421    pub meta: SessionMeta,
1422
1423    /// The tokens used for authentication.
1424    #[serde(flatten)]
1425    pub tokens: SessionTokens,
1426}
1427
1428/// The data necessary to validate a response from the Token endpoint in the
1429/// Authorization Code flow.
1430#[derive(Debug)]
1431struct AuthorizationValidationData {
1432    /// The metadata of the server,
1433    server_metadata: AuthorizationServerMetadata,
1434
1435    /// The device ID used in the scope.
1436    device_id: OwnedDeviceId,
1437
1438    /// The URI where the end-user will be redirected after authorization.
1439    redirect_uri: RedirectUrl,
1440
1441    /// A string to correlate the authorization request to the token request.
1442    pkce_verifier: PkceCodeVerifier,
1443}
1444
1445/// The data returned by the server in the redirect URI after a successful
1446/// authorization.
1447#[derive(Debug, Clone)]
1448enum AuthorizationResponse {
1449    /// A successful response.
1450    Success(AuthorizationCode),
1451
1452    /// An error response.
1453    Error(AuthorizationError),
1454}
1455
1456impl AuthorizationResponse {
1457    /// Deserialize an `AuthorizationResponse` from a [`UrlOrQuery`].
1458    ///
1459    /// Returns an error if the URL or query doesn't have the expected format.
1460    fn parse_url_or_query(url_or_query: &UrlOrQuery) -> Result<Self, RedirectUriQueryParseError> {
1461        let query = url_or_query.query().ok_or(RedirectUriQueryParseError::MissingQuery)?;
1462        Self::parse_query(query)
1463    }
1464
1465    /// Deserialize an `AuthorizationResponse` from the query part of a URI.
1466    ///
1467    /// Returns an error if the query doesn't have the expected format.
1468    fn parse_query(query: &str) -> Result<Self, RedirectUriQueryParseError> {
1469        // For some reason deserializing the enum with `serde(untagged)` doesn't work,
1470        // so let's try both variants separately.
1471        if let Ok(code) = serde_html_form::from_str(query) {
1472            return Ok(AuthorizationResponse::Success(code));
1473        }
1474        if let Ok(error) = serde_html_form::from_str(query) {
1475            return Ok(AuthorizationResponse::Error(error));
1476        }
1477
1478        Err(RedirectUriQueryParseError::UnknownFormat)
1479    }
1480}
1481
1482/// The data returned by the server in the redirect URI after a successful
1483/// authorization.
1484#[derive(Debug, Clone, Deserialize)]
1485struct AuthorizationCode {
1486    /// The code to use to retrieve the access token.
1487    code: String,
1488    /// The unique identifier for this transaction.
1489    state: CsrfToken,
1490}
1491
1492/// The data returned by the server in the redirect URI after an authorization
1493/// error.
1494#[derive(Debug, Clone, Deserialize)]
1495struct AuthorizationError {
1496    /// The error.
1497    #[serde(flatten)]
1498    error: StandardErrorResponse<error::AuthorizationCodeErrorResponseType>,
1499    /// The unique identifier for this transaction.
1500    state: CsrfToken,
1501}
1502
1503fn hash_str(x: &str) -> impl fmt::LowerHex {
1504    sha2::Sha256::new().chain_update(x).finalize()
1505}
1506
1507/// Data to register or restore a client.
1508#[derive(Debug, Clone)]
1509pub struct ClientRegistrationData {
1510    /// The metadata to use to register the client when using dynamic client
1511    /// registration.
1512    pub metadata: Raw<ClientMetadata>,
1513
1514    /// Static registrations for servers that don't support dynamic registration
1515    /// but provide a client ID out-of-band.
1516    ///
1517    /// The keys of the map should be the URLs of the homeservers, but keys
1518    /// using `issuer` URLs are also supported.
1519    pub static_registrations: Option<HashMap<Url, ClientId>>,
1520}
1521
1522impl ClientRegistrationData {
1523    /// Construct a [`ClientRegistrationData`] with the given metadata and no
1524    /// static registrations.
1525    pub fn new(metadata: Raw<ClientMetadata>) -> Self {
1526        Self { metadata, static_registrations: None }
1527    }
1528}
1529
1530impl From<Raw<ClientMetadata>> for ClientRegistrationData {
1531    fn from(value: Raw<ClientMetadata>) -> Self {
1532        Self::new(value)
1533    }
1534}
1535
1536/// A full URL or just the query part of a URL.
1537#[derive(Debug, Clone, PartialEq, Eq)]
1538pub enum UrlOrQuery {
1539    /// A full URL.
1540    Url(Url),
1541
1542    /// The query part of a URL.
1543    Query(String),
1544}
1545
1546impl UrlOrQuery {
1547    /// Get the query part of this [`UrlOrQuery`].
1548    ///
1549    /// If this is a [`Url`], this extracts the query.
1550    pub fn query(&self) -> Option<&str> {
1551        match self {
1552            Self::Url(url) => url.query(),
1553            Self::Query(query) => Some(query),
1554        }
1555    }
1556}
1557
1558impl From<Url> for UrlOrQuery {
1559    fn from(value: Url) -> Self {
1560        Self::Url(value)
1561    }
1562}