matrix_sdk/client/builder/
mod.rs

1// Copyright 2022 The Matrix.org Foundation C.I.C.
2// Copyright 2022 Kévin Commaille
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
16mod homeserver_config;
17
18use std::{fmt, sync::Arc};
19
20use homeserver_config::*;
21use matrix_sdk_base::{store::StoreConfig, BaseClient};
22use ruma::{
23    api::{error::FromHttpResponseError, MatrixVersion},
24    OwnedServerName, ServerName,
25};
26use thiserror::Error;
27use tokio::sync::{broadcast, Mutex, OnceCell};
28use tracing::{debug, field::debug, instrument, Span};
29
30use super::{Client, ClientInner};
31#[cfg(feature = "experimental-oidc")]
32use crate::authentication::oidc::OidcCtx;
33#[cfg(feature = "e2e-encryption")]
34use crate::crypto::{CollectStrategy, TrustRequirement};
35#[cfg(feature = "e2e-encryption")]
36use crate::encryption::EncryptionSettings;
37#[cfg(not(target_arch = "wasm32"))]
38use crate::http_client::HttpSettings;
39use crate::{
40    authentication::AuthCtx, client::ClientServerCapabilities, config::RequestConfig,
41    error::RumaApiError, http_client::HttpClient, send_queue::SendQueueData,
42    sliding_sync::VersionBuilder as SlidingSyncVersionBuilder, HttpError, IdParseError,
43};
44
45/// Builder that allows creating and configuring various parts of a [`Client`].
46///
47/// When setting the `StateStore` it is up to the user to open/connect
48/// the storage backend before client creation.
49///
50/// # Examples
51///
52/// ```
53/// use matrix_sdk::Client;
54/// // To pass all the request through mitmproxy set the proxy and disable SSL
55/// // verification
56///
57/// let client_builder = Client::builder()
58///     .proxy("http://localhost:8080")
59///     .disable_ssl_verification();
60/// ```
61///
62/// # Example for using a custom http client
63///
64/// Note: setting a custom http client will ignore `user_agent`, `proxy`, and
65/// `disable_ssl_verification` - you'd need to set these yourself if you want
66/// them.
67///
68/// ```
69/// use std::sync::Arc;
70///
71/// use matrix_sdk::Client;
72///
73/// // setting up a custom http client
74/// let reqwest_builder = reqwest::ClientBuilder::new()
75///     .https_only(true)
76///     .no_proxy()
77///     .user_agent("MyApp/v3.0");
78///
79/// let client_builder =
80///     Client::builder().http_client(reqwest_builder.build()?);
81/// # anyhow::Ok(())
82/// ```
83#[must_use]
84#[derive(Clone, Debug)]
85pub struct ClientBuilder {
86    homeserver_cfg: Option<HomeserverConfig>,
87    sliding_sync_version_builder: SlidingSyncVersionBuilder,
88    http_cfg: Option<HttpConfig>,
89    store_config: BuilderStoreConfig,
90    request_config: RequestConfig,
91    respect_login_well_known: bool,
92    server_versions: Option<Box<[MatrixVersion]>>,
93    handle_refresh_tokens: bool,
94    base_client: Option<BaseClient>,
95    #[cfg(feature = "e2e-encryption")]
96    encryption_settings: EncryptionSettings,
97    #[cfg(feature = "e2e-encryption")]
98    room_key_recipient_strategy: CollectStrategy,
99    #[cfg(feature = "e2e-encryption")]
100    decryption_trust_requirement: TrustRequirement,
101    cross_process_store_locks_holder_name: String,
102}
103
104impl ClientBuilder {
105    const DEFAULT_CROSS_PROCESS_STORE_LOCKS_HOLDER_NAME: &str = "main";
106
107    pub(crate) fn new() -> Self {
108        Self {
109            homeserver_cfg: None,
110            sliding_sync_version_builder: SlidingSyncVersionBuilder::Native,
111            http_cfg: None,
112            store_config: BuilderStoreConfig::Custom(StoreConfig::new(
113                Self::DEFAULT_CROSS_PROCESS_STORE_LOCKS_HOLDER_NAME.to_owned(),
114            )),
115            request_config: Default::default(),
116            respect_login_well_known: true,
117            server_versions: None,
118            handle_refresh_tokens: false,
119            base_client: None,
120            #[cfg(feature = "e2e-encryption")]
121            encryption_settings: Default::default(),
122            #[cfg(feature = "e2e-encryption")]
123            room_key_recipient_strategy: Default::default(),
124            #[cfg(feature = "e2e-encryption")]
125            decryption_trust_requirement: TrustRequirement::Untrusted,
126            cross_process_store_locks_holder_name:
127                Self::DEFAULT_CROSS_PROCESS_STORE_LOCKS_HOLDER_NAME.to_owned(),
128        }
129    }
130
131    /// Set the homeserver URL to use.
132    ///
133    /// The following methods are mutually exclusive: [`Self::homeserver_url`],
134    /// [`Self::server_name`] [`Self::insecure_server_name_no_tls`],
135    /// [`Self::server_name_or_homeserver_url`].
136    /// If you set more than one, then whatever was set last will be used.
137    pub fn homeserver_url(mut self, url: impl AsRef<str>) -> Self {
138        self.homeserver_cfg = Some(HomeserverConfig::HomeserverUrl(url.as_ref().to_owned()));
139        self
140    }
141
142    /// Set the server name to discover the homeserver from.
143    ///
144    /// We assume we can connect in HTTPS to that server. If that's not the
145    /// case, prefer using [`Self::insecure_server_name_no_tls`].
146    ///
147    /// The following methods are mutually exclusive: [`Self::homeserver_url`],
148    /// [`Self::server_name`] [`Self::insecure_server_name_no_tls`],
149    /// [`Self::server_name_or_homeserver_url`].
150    /// If you set more than one, then whatever was set last will be used.
151    pub fn server_name(mut self, server_name: &ServerName) -> Self {
152        self.homeserver_cfg = Some(HomeserverConfig::ServerName {
153            server: server_name.to_owned(),
154            // Assume HTTPS if not specified.
155            protocol: UrlScheme::Https,
156        });
157        self
158    }
159
160    /// Set the server name to discover the homeserver from, assuming an HTTP
161    /// (not secured) scheme. This also relaxes OIDC discovery checks to allow
162    /// HTTP schemes.
163    ///
164    /// The following methods are mutually exclusive: [`Self::homeserver_url`],
165    /// [`Self::server_name`] [`Self::insecure_server_name_no_tls`],
166    /// [`Self::server_name_or_homeserver_url`].
167    /// If you set more than one, then whatever was set last will be used.
168    pub fn insecure_server_name_no_tls(mut self, server_name: &ServerName) -> Self {
169        self.homeserver_cfg = Some(HomeserverConfig::ServerName {
170            server: server_name.to_owned(),
171            protocol: UrlScheme::Http,
172        });
173        self
174    }
175
176    /// Set the server name to discover the homeserver from, falling back to
177    /// using it as a homeserver URL if discovery fails. When falling back to a
178    /// homeserver URL, a check is made to ensure that the server exists (unlike
179    /// [`Self::homeserver_url`], so you can guarantee that the client is ready
180    /// to use.
181    ///
182    /// The following methods are mutually exclusive: [`Self::homeserver_url`],
183    /// [`Self::server_name`] [`Self::insecure_server_name_no_tls`],
184    /// [`Self::server_name_or_homeserver_url`].
185    /// If you set more than one, then whatever was set last will be used.
186    pub fn server_name_or_homeserver_url(mut self, server_name_or_url: impl AsRef<str>) -> Self {
187        self.homeserver_cfg = Some(HomeserverConfig::ServerNameOrHomeserverUrl(
188            server_name_or_url.as_ref().to_owned(),
189        ));
190        self
191    }
192
193    /// Set sliding sync to a specific version.
194    pub fn sliding_sync_version_builder(
195        mut self,
196        version_builder: SlidingSyncVersionBuilder,
197    ) -> Self {
198        self.sliding_sync_version_builder = version_builder;
199        self
200    }
201
202    /// Set up the store configuration for a SQLite store.
203    #[cfg(feature = "sqlite")]
204    pub fn sqlite_store(
205        mut self,
206        path: impl AsRef<std::path::Path>,
207        passphrase: Option<&str>,
208    ) -> Self {
209        self.store_config = BuilderStoreConfig::Sqlite {
210            path: path.as_ref().to_owned(),
211            cache_path: None,
212            passphrase: passphrase.map(ToOwned::to_owned),
213        };
214        self
215    }
216
217    /// Set up the store configuration for a SQLite store with cached data
218    /// separated out from state/crypto data.
219    #[cfg(feature = "sqlite")]
220    pub fn sqlite_store_with_cache_path(
221        mut self,
222        path: impl AsRef<std::path::Path>,
223        cache_path: impl AsRef<std::path::Path>,
224        passphrase: Option<&str>,
225    ) -> Self {
226        self.store_config = BuilderStoreConfig::Sqlite {
227            path: path.as_ref().to_owned(),
228            cache_path: Some(cache_path.as_ref().to_owned()),
229            passphrase: passphrase.map(ToOwned::to_owned),
230        };
231        self
232    }
233
234    /// Set up the store configuration for a IndexedDB store.
235    #[cfg(feature = "indexeddb")]
236    pub fn indexeddb_store(mut self, name: &str, passphrase: Option<&str>) -> Self {
237        self.store_config = BuilderStoreConfig::IndexedDb {
238            name: name.to_owned(),
239            passphrase: passphrase.map(ToOwned::to_owned),
240        };
241        self
242    }
243
244    /// Set up the store configuration.
245    ///
246    /// The easiest way to get a [`StoreConfig`] is to use the
247    /// `make_store_config` method from one of the store crates.
248    ///
249    /// # Arguments
250    ///
251    /// * `store_config` - The configuration of the store.
252    ///
253    /// # Examples
254    ///
255    /// ```
256    /// # use matrix_sdk_base::store::MemoryStore;
257    /// # let custom_state_store = MemoryStore::new();
258    /// use matrix_sdk::{config::StoreConfig, Client};
259    ///
260    /// let store_config =
261    ///     StoreConfig::new("cross-process-store-locks-holder-name".to_owned())
262    ///         .state_store(custom_state_store);
263    /// let client_builder = Client::builder().store_config(store_config);
264    /// ```
265    pub fn store_config(mut self, store_config: StoreConfig) -> Self {
266        self.store_config = BuilderStoreConfig::Custom(store_config);
267        self
268    }
269
270    /// Update the client's homeserver URL with the discovery information
271    /// present in the login response, if any.
272    pub fn respect_login_well_known(mut self, value: bool) -> Self {
273        self.respect_login_well_known = value;
274        self
275    }
276
277    /// Set the default timeout, fail and retry behavior for all HTTP requests.
278    pub fn request_config(mut self, request_config: RequestConfig) -> Self {
279        self.request_config = request_config;
280        self
281    }
282
283    /// Set the proxy through which all the HTTP requests should go.
284    ///
285    /// Note, only HTTP proxies are supported.
286    ///
287    /// # Arguments
288    ///
289    /// * `proxy` - The HTTP URL of the proxy.
290    ///
291    /// # Examples
292    ///
293    /// ```no_run
294    /// use matrix_sdk::Client;
295    ///
296    /// let client_config = Client::builder().proxy("http://localhost:8080");
297    /// ```
298    #[cfg(not(target_arch = "wasm32"))]
299    pub fn proxy(mut self, proxy: impl AsRef<str>) -> Self {
300        self.http_settings().proxy = Some(proxy.as_ref().to_owned());
301        self
302    }
303
304    /// Disable SSL verification for the HTTP requests.
305    #[cfg(not(target_arch = "wasm32"))]
306    pub fn disable_ssl_verification(mut self) -> Self {
307        self.http_settings().disable_ssl_verification = true;
308        self
309    }
310
311    /// Set a custom HTTP user agent for the client.
312    #[cfg(not(target_arch = "wasm32"))]
313    pub fn user_agent(mut self, user_agent: impl AsRef<str>) -> Self {
314        self.http_settings().user_agent = Some(user_agent.as_ref().to_owned());
315        self
316    }
317
318    /// Add the given list of certificates to the certificate store of the HTTP
319    /// client.
320    ///
321    /// These additional certificates will be trusted and considered when
322    /// establishing a HTTP request.
323    ///
324    /// Internally this will call the
325    /// [`reqwest::ClientBuilder::add_root_certificate()`] method.
326    #[cfg(not(target_arch = "wasm32"))]
327    pub fn add_root_certificates(mut self, certificates: Vec<reqwest::Certificate>) -> Self {
328        self.http_settings().additional_root_certificates = certificates;
329        self
330    }
331
332    /// Don't trust any system root certificates, only trust the certificates
333    /// provided through
334    /// [`add_root_certificates`][ClientBuilder::add_root_certificates].
335    #[cfg(not(target_arch = "wasm32"))]
336    pub fn disable_built_in_root_certificates(mut self) -> Self {
337        self.http_settings().disable_built_in_root_certificates = true;
338        self
339    }
340
341    /// Specify a [`reqwest::Client`] instance to handle sending requests and
342    /// receiving responses.
343    ///
344    /// This method is mutually exclusive with
345    /// [`proxy()`][ClientBuilder::proxy],
346    /// [`disable_ssl_verification`][ClientBuilder::disable_ssl_verification],
347    /// [`add_root_certificates`][ClientBuilder::add_root_certificates],
348    /// [`disable_built_in_root_certificates`][ClientBuilder::disable_built_in_root_certificates],
349    /// and [`user_agent()`][ClientBuilder::user_agent].
350    pub fn http_client(mut self, client: reqwest::Client) -> Self {
351        self.http_cfg = Some(HttpConfig::Custom(client));
352        self
353    }
354
355    /// Specify the Matrix versions supported by the homeserver manually, rather
356    /// than `build()` doing it using a `get_supported_versions` request.
357    ///
358    /// This is helpful for test code that doesn't care to mock that endpoint.
359    pub fn server_versions(mut self, value: impl IntoIterator<Item = MatrixVersion>) -> Self {
360        self.server_versions = Some(value.into_iter().collect());
361        self
362    }
363
364    #[cfg(not(target_arch = "wasm32"))]
365    fn http_settings(&mut self) -> &mut HttpSettings {
366        self.http_cfg.get_or_insert_with(Default::default).settings()
367    }
368
369    /// Handle [refreshing access tokens] automatically.
370    ///
371    /// By default, the `Client` forwards any error and doesn't handle errors
372    /// with the access token, which means that
373    /// [`Client::refresh_access_token()`] needs to be called manually to
374    /// refresh access tokens.
375    ///
376    /// Enabling this setting means that the `Client` will try to refresh the
377    /// token automatically, which means that:
378    ///
379    /// * If refreshing the token fails, the error is forwarded, so any endpoint
380    ///   can return [`HttpError::RefreshToken`]. If an [`UnknownToken`] error
381    ///   is encountered, it means that the user needs to be logged in again.
382    ///
383    /// * The access token and refresh token need to be watched for changes,
384    ///   using the authentication API's `session_tokens_stream()` for example,
385    ///   to be able to [restore the session] later.
386    ///
387    /// [refreshing access tokens]: https://spec.matrix.org/v1.3/client-server-api/#refreshing-access-tokens
388    /// [`UnknownToken`]: ruma::api::client::error::ErrorKind::UnknownToken
389    /// [restore the session]: Client::restore_session
390    pub fn handle_refresh_tokens(mut self) -> Self {
391        self.handle_refresh_tokens = true;
392        self
393    }
394
395    /// Public for test only
396    #[doc(hidden)]
397    pub fn base_client(mut self, base_client: BaseClient) -> Self {
398        self.base_client = Some(base_client);
399        self
400    }
401
402    /// Enables specific encryption settings that will persist throughout the
403    /// entire lifetime of the `Client`.
404    #[cfg(feature = "e2e-encryption")]
405    pub fn with_encryption_settings(mut self, settings: EncryptionSettings) -> Self {
406        self.encryption_settings = settings;
407        self
408    }
409
410    /// Set the strategy to be used for picking recipient devices, when sending
411    /// an encrypted message.
412    #[cfg(feature = "e2e-encryption")]
413    pub fn with_room_key_recipient_strategy(mut self, strategy: CollectStrategy) -> Self {
414        self.room_key_recipient_strategy = strategy;
415        self
416    }
417
418    /// Set the trust requirement to be used when decrypting events.
419    #[cfg(feature = "e2e-encryption")]
420    pub fn with_decryption_trust_requirement(
421        mut self,
422        trust_requirement: TrustRequirement,
423    ) -> Self {
424        self.decryption_trust_requirement = trust_requirement;
425        self
426    }
427
428    /// Set the cross-process store locks holder name.
429    ///
430    /// The SDK provides cross-process store locks (see
431    /// [`matrix_sdk_common::store_locks::CrossProcessStoreLock`]). The
432    /// `holder_name` will be the value used for all cross-process store locks
433    /// used by the `Client` being built.
434    ///
435    /// If 2 concurrent `Client`s are running in 2 different process, this
436    /// method must be called with different `hold_name` values.
437    pub fn cross_process_store_locks_holder_name(mut self, holder_name: String) -> Self {
438        self.cross_process_store_locks_holder_name = holder_name;
439        self
440    }
441
442    /// Create a [`Client`] with the options set on this builder.
443    ///
444    /// # Errors
445    ///
446    /// This method can fail for two general reasons:
447    ///
448    /// * Invalid input: a missing or invalid homeserver URL or invalid proxy
449    ///   URL
450    /// * HTTP error: If you supplied a user ID instead of a homeserver URL, a
451    ///   server discovery request is made which can fail; if you didn't set
452    ///   [`server_versions(false)`][Self::server_versions], that amounts to
453    ///   another request that can fail
454    #[instrument(skip_all, target = "matrix_sdk::client", fields(homeserver))]
455    pub async fn build(self) -> Result<Client, ClientBuildError> {
456        debug!("Starting to build the Client");
457
458        let homeserver_cfg = self.homeserver_cfg.ok_or(ClientBuildError::MissingHomeserver)?;
459        Span::current().record("homeserver", debug(&homeserver_cfg));
460
461        #[cfg_attr(target_arch = "wasm32", allow(clippy::infallible_destructuring_match))]
462        let inner_http_client = match self.http_cfg.unwrap_or_default() {
463            #[cfg(not(target_arch = "wasm32"))]
464            HttpConfig::Settings(mut settings) => {
465                settings.timeout = self.request_config.timeout;
466                settings.make_client()?
467            }
468            HttpConfig::Custom(c) => c,
469        };
470
471        let base_client = if let Some(base_client) = self.base_client {
472            base_client
473        } else {
474            #[allow(unused_mut)]
475            let mut client = BaseClient::with_store_config(
476                build_store_config(self.store_config, &self.cross_process_store_locks_holder_name)
477                    .await?,
478            );
479
480            #[cfg(feature = "e2e-encryption")]
481            {
482                client.room_key_recipient_strategy = self.room_key_recipient_strategy;
483                client.decryption_trust_requirement = self.decryption_trust_requirement;
484            }
485
486            client
487        };
488
489        let http_client = HttpClient::new(inner_http_client.clone(), self.request_config);
490
491        #[allow(unused_variables)]
492        let HomeserverDiscoveryResult { server, homeserver, well_known, supported_versions } =
493            homeserver_cfg.discover(&http_client).await?;
494
495        let sliding_sync_version = {
496            let supported_versions = match supported_versions {
497                Some(versions) => Some(versions),
498                None if self.sliding_sync_version_builder.needs_get_supported_versions() => {
499                    Some(get_supported_versions(&homeserver, &http_client).await?)
500                }
501                None => None,
502            };
503
504            let version = self
505                .sliding_sync_version_builder
506                .build(well_known.as_ref(), supported_versions.as_ref())?;
507
508            tracing::info!(?version, "selected sliding sync version");
509
510            version
511        };
512
513        #[cfg(feature = "experimental-oidc")]
514        let allow_insecure_oidc = homeserver.scheme() == "http";
515
516        let auth_ctx = Arc::new(AuthCtx {
517            handle_refresh_tokens: self.handle_refresh_tokens,
518            refresh_token_lock: Arc::new(Mutex::new(Ok(()))),
519            session_change_sender: broadcast::Sender::new(1),
520            auth_data: OnceCell::default(),
521            reload_session_callback: OnceCell::default(),
522            save_session_callback: OnceCell::default(),
523            #[cfg(feature = "experimental-oidc")]
524            oidc: OidcCtx::new(allow_insecure_oidc),
525        });
526
527        // Enable the send queue by default.
528        let send_queue = Arc::new(SendQueueData::new(true));
529
530        let server_capabilities = ClientServerCapabilities {
531            server_versions: self.server_versions,
532            unstable_features: None,
533        };
534
535        let event_cache = OnceCell::new();
536        let inner = ClientInner::new(
537            auth_ctx,
538            server,
539            homeserver,
540            sliding_sync_version,
541            http_client,
542            base_client,
543            server_capabilities,
544            self.respect_login_well_known,
545            event_cache,
546            send_queue,
547            #[cfg(feature = "e2e-encryption")]
548            self.encryption_settings,
549            self.cross_process_store_locks_holder_name,
550        )
551        .await;
552
553        debug!("Done building the Client");
554
555        Ok(Client { inner })
556    }
557}
558
559/// Creates a server name from a user supplied string. The string is first
560/// sanitized by removing whitespace, the http(s) scheme and any trailing
561/// slashes before being parsed.
562pub fn sanitize_server_name(s: &str) -> crate::Result<OwnedServerName, IdParseError> {
563    ServerName::parse(
564        s.trim().trim_start_matches("http://").trim_start_matches("https://").trim_end_matches('/'),
565    )
566}
567
568#[allow(clippy::unused_async, unused)] // False positive when building with !sqlite & !indexeddb
569async fn build_store_config(
570    builder_config: BuilderStoreConfig,
571    cross_process_store_locks_holder_name: &str,
572) -> Result<StoreConfig, ClientBuildError> {
573    #[allow(clippy::infallible_destructuring_match)]
574    let store_config = match builder_config {
575        #[cfg(feature = "sqlite")]
576        BuilderStoreConfig::Sqlite { path, cache_path, passphrase } => {
577            let store_config = StoreConfig::new(cross_process_store_locks_holder_name.to_owned())
578                .state_store(
579                    matrix_sdk_sqlite::SqliteStateStore::open(&path, passphrase.as_deref()).await?,
580                )
581                .event_cache_store(
582                    matrix_sdk_sqlite::SqliteEventCacheStore::open(
583                        cache_path.as_ref().unwrap_or(&path),
584                        passphrase.as_deref(),
585                    )
586                    .await?,
587                );
588
589            #[cfg(feature = "e2e-encryption")]
590            let store_config = store_config.crypto_store(
591                matrix_sdk_sqlite::SqliteCryptoStore::open(&path, passphrase.as_deref()).await?,
592            );
593
594            store_config
595        }
596
597        #[cfg(feature = "indexeddb")]
598        BuilderStoreConfig::IndexedDb { name, passphrase } => {
599            build_indexeddb_store_config(
600                &name,
601                passphrase.as_deref(),
602                cross_process_store_locks_holder_name,
603            )
604            .await?
605        }
606
607        BuilderStoreConfig::Custom(config) => config,
608    };
609    Ok(store_config)
610}
611
612// The indexeddb stores only implement `IntoStateStore` and `IntoCryptoStore` on
613// wasm32, so this only compiles there.
614#[cfg(all(target_arch = "wasm32", feature = "indexeddb"))]
615async fn build_indexeddb_store_config(
616    name: &str,
617    passphrase: Option<&str>,
618    cross_process_store_locks_holder_name: &str,
619) -> Result<StoreConfig, ClientBuildError> {
620    let cross_process_store_locks_holder_name = cross_process_store_locks_holder_name.to_owned();
621
622    #[cfg(feature = "e2e-encryption")]
623    let store_config = {
624        let (state_store, crypto_store) =
625            matrix_sdk_indexeddb::open_stores_with_name(name, passphrase).await?;
626        StoreConfig::new(cross_process_store_locks_holder_name)
627            .state_store(state_store)
628            .crypto_store(crypto_store)
629    };
630
631    #[cfg(not(feature = "e2e-encryption"))]
632    let store_config = {
633        let state_store = matrix_sdk_indexeddb::open_state_store(name, passphrase).await?;
634        StoreConfig::new(cross_process_store_locks_holder_name).state_store(state_store)
635    };
636
637    let store_config = {
638        tracing::warn!("The IndexedDB backend does not implement an event cache store, falling back to the in-memory event cache store…");
639        store_config.event_cache_store(matrix_sdk_base::event_cache::store::MemoryStore::new())
640    };
641
642    Ok(store_config)
643}
644
645#[cfg(all(not(target_arch = "wasm32"), feature = "indexeddb"))]
646#[allow(clippy::unused_async)]
647async fn build_indexeddb_store_config(
648    _name: &str,
649    _passphrase: Option<&str>,
650    _event_cache_store_lock_holder_name: &str,
651) -> Result<StoreConfig, ClientBuildError> {
652    panic!("the IndexedDB is only available on the 'wasm32' arch")
653}
654
655#[derive(Clone, Debug)]
656enum HttpConfig {
657    #[cfg(not(target_arch = "wasm32"))]
658    Settings(HttpSettings),
659    Custom(reqwest::Client),
660}
661
662#[cfg(not(target_arch = "wasm32"))]
663impl HttpConfig {
664    fn settings(&mut self) -> &mut HttpSettings {
665        match self {
666            Self::Settings(s) => s,
667            Self::Custom(_) => {
668                *self = Self::default();
669                match self {
670                    Self::Settings(s) => s,
671                    Self::Custom(_) => unreachable!(),
672                }
673            }
674        }
675    }
676}
677
678impl Default for HttpConfig {
679    fn default() -> Self {
680        #[cfg(not(target_arch = "wasm32"))]
681        return Self::Settings(HttpSettings::default());
682
683        #[cfg(target_arch = "wasm32")]
684        return Self::Custom(reqwest::Client::new());
685    }
686}
687
688#[derive(Clone)]
689enum BuilderStoreConfig {
690    #[cfg(feature = "sqlite")]
691    Sqlite {
692        path: std::path::PathBuf,
693        cache_path: Option<std::path::PathBuf>,
694        passphrase: Option<String>,
695    },
696    #[cfg(feature = "indexeddb")]
697    IndexedDb {
698        name: String,
699        passphrase: Option<String>,
700    },
701    Custom(StoreConfig),
702}
703
704#[cfg(not(tarpaulin_include))]
705impl fmt::Debug for BuilderStoreConfig {
706    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
707        #[allow(clippy::infallible_destructuring_match)]
708        match self {
709            #[cfg(feature = "sqlite")]
710            Self::Sqlite { path, .. } => {
711                f.debug_struct("Sqlite").field("path", path).finish_non_exhaustive()
712            }
713            #[cfg(feature = "indexeddb")]
714            Self::IndexedDb { name, .. } => {
715                f.debug_struct("IndexedDb").field("name", name).finish_non_exhaustive()
716            }
717            Self::Custom(store_config) => f.debug_tuple("Custom").field(store_config).finish(),
718        }
719    }
720}
721
722/// Errors that can happen in [`ClientBuilder::build`].
723#[derive(Debug, Error)]
724pub enum ClientBuildError {
725    /// No homeserver or user ID was configured
726    #[error("no homeserver or user ID was configured")]
727    MissingHomeserver,
728
729    /// The supplied server name was invalid.
730    #[error("The supplied server name is invalid")]
731    InvalidServerName,
732
733    /// Error looking up the .well-known endpoint on auto-discovery
734    #[error("Error looking up the .well-known endpoint on auto-discovery")]
735    AutoDiscovery(FromHttpResponseError<RumaApiError>),
736
737    /// Error when building the sliding sync version.
738    #[error(transparent)]
739    SlidingSyncVersion(#[from] crate::sliding_sync::VersionBuilderError),
740
741    /// An error encountered when trying to parse the homeserver url.
742    #[error(transparent)]
743    Url(#[from] url::ParseError),
744
745    /// Error doing an HTTP request.
746    #[error(transparent)]
747    Http(#[from] HttpError),
748
749    /// Error opening the indexeddb store.
750    #[cfg(feature = "indexeddb")]
751    #[error(transparent)]
752    IndexeddbStore(#[from] matrix_sdk_indexeddb::OpenStoreError),
753
754    /// Error opening the sqlite store.
755    #[cfg(feature = "sqlite")]
756    #[error(transparent)]
757    SqliteStore(#[from] matrix_sdk_sqlite::OpenStoreError),
758}
759
760// The http mocking library is not supported for wasm32
761#[cfg(all(test, not(target_arch = "wasm32")))]
762pub(crate) mod tests {
763    use assert_matches::assert_matches;
764    use matrix_sdk_test::{async_test, test_json};
765    use serde_json::{json_internal, Value as JsonValue};
766    use url::Url;
767    use wiremock::{
768        matchers::{method, path},
769        Mock, MockServer, ResponseTemplate,
770    };
771
772    use super::*;
773    use crate::sliding_sync::Version as SlidingSyncVersion;
774
775    #[test]
776    fn test_sanitize_server_name() {
777        assert_eq!(sanitize_server_name("matrix.org").unwrap().as_str(), "matrix.org");
778        assert_eq!(sanitize_server_name("https://matrix.org").unwrap().as_str(), "matrix.org");
779        assert_eq!(sanitize_server_name("http://matrix.org").unwrap().as_str(), "matrix.org");
780        assert_eq!(
781            sanitize_server_name("https://matrix.server.org").unwrap().as_str(),
782            "matrix.server.org"
783        );
784        assert_eq!(
785            sanitize_server_name("https://matrix.server.org/").unwrap().as_str(),
786            "matrix.server.org"
787        );
788        assert_eq!(
789            sanitize_server_name("  https://matrix.server.org// ").unwrap().as_str(),
790            "matrix.server.org"
791        );
792        assert_matches!(sanitize_server_name("https://matrix.server.org/something"), Err(_))
793    }
794
795    // Note: Due to a limitation of the http mocking library the following tests all
796    // supply an http:// url, to `server_name_or_homeserver_url` rather than the plain server name,
797    // otherwise  the builder will prepend https:// and the request will fail. In practice, this
798    // isn't a problem as the builder first strips the scheme and then checks if the
799    // name is a valid server name, so it is a close enough approximation.
800
801    #[async_test]
802    async fn test_discovery_invalid_server() {
803        // Given a new client builder.
804        let mut builder = ClientBuilder::new();
805
806        // When building a client with an invalid server name.
807        builder = builder.server_name_or_homeserver_url("⚠️ This won't work 🚫");
808        let error = builder.build().await.unwrap_err();
809
810        // Then the operation should fail due to the invalid server name.
811        assert_matches!(error, ClientBuildError::InvalidServerName);
812    }
813
814    #[async_test]
815    async fn test_discovery_no_server() {
816        // Given a new client builder.
817        let mut builder = ClientBuilder::new();
818
819        // When building a client with a valid server name that doesn't exist.
820        builder = builder.server_name_or_homeserver_url("localhost:3456");
821        let error = builder.build().await.unwrap_err();
822
823        // Then the operation should fail with an HTTP error.
824        println!("{error}");
825        assert_matches!(error, ClientBuildError::Http(_));
826    }
827
828    #[async_test]
829    async fn test_discovery_web_server() {
830        // Given a random web server that isn't a Matrix homeserver or hosting the
831        // well-known file for one.
832        let server = MockServer::start().await;
833        let mut builder = ClientBuilder::new();
834
835        // When building a client with the server's URL.
836        builder = builder.server_name_or_homeserver_url(server.uri());
837        let error = builder.build().await.unwrap_err();
838
839        // Then the operation should fail with a server discovery error.
840        assert_matches!(error, ClientBuildError::AutoDiscovery(FromHttpResponseError::Server(_)));
841    }
842
843    #[async_test]
844    async fn test_discovery_direct_legacy() {
845        // Given a homeserver without a well-known file.
846        let homeserver = make_mock_homeserver().await;
847        let mut builder = ClientBuilder::new();
848
849        // When building a client with the server's URL.
850        builder = builder.server_name_or_homeserver_url(homeserver.uri());
851        let _client = builder.build().await.unwrap();
852
853        // Then a client should be built with native support for sliding sync.
854        assert!(_client.sliding_sync_version().is_native());
855    }
856
857    #[async_test]
858    async fn test_discovery_direct_legacy_custom_proxy() {
859        // Given a homeserver without a well-known file and with a custom sliding sync
860        // proxy injected.
861        let homeserver = make_mock_homeserver().await;
862        let mut builder = ClientBuilder::new();
863        let url = {
864            let url = Url::parse("https://localhost:1234").unwrap();
865            builder = builder.sliding_sync_version_builder(SlidingSyncVersionBuilder::Proxy {
866                url: url.clone(),
867            });
868
869            url
870        };
871
872        // When building a client with the server's URL.
873        builder = builder.server_name_or_homeserver_url(homeserver.uri());
874        let client = builder.build().await.unwrap();
875
876        // Then a client should be built with support for sliding sync.
877        assert_matches!(
878            client.sliding_sync_version(),
879            SlidingSyncVersion::Proxy { url: given_url } => {
880                assert_eq!(given_url, url);
881            }
882        );
883    }
884
885    #[async_test]
886    async fn test_discovery_well_known_parse_error() {
887        // Given a base server with a well-known file that has errors.
888        let server = MockServer::start().await;
889        let homeserver = make_mock_homeserver().await;
890        let mut builder = ClientBuilder::new();
891
892        let well_known = make_well_known_json(&homeserver.uri(), None);
893        let bad_json = well_known.to_string().replace(',', "");
894        Mock::given(method("GET"))
895            .and(path("/.well-known/matrix/client"))
896            .respond_with(ResponseTemplate::new(200).set_body_json(bad_json))
897            .mount(&server)
898            .await;
899
900        // When building a client with the base server.
901        builder = builder.server_name_or_homeserver_url(server.uri());
902        let error = builder.build().await.unwrap_err();
903
904        // Then the operation should fail due to the well-known file's contents.
905        assert_matches!(
906            error,
907            ClientBuildError::AutoDiscovery(FromHttpResponseError::Deserialization(_))
908        );
909    }
910
911    #[async_test]
912    async fn test_discovery_well_known_legacy() {
913        // Given a base server with a well-known file that points to a homeserver that
914        // doesn't support sliding sync.
915        let server = MockServer::start().await;
916        let homeserver = make_mock_homeserver().await;
917        let mut builder = ClientBuilder::new();
918
919        Mock::given(method("GET"))
920            .and(path("/.well-known/matrix/client"))
921            .respond_with(
922                ResponseTemplate::new(200)
923                    .set_body_json(make_well_known_json(&homeserver.uri(), None)),
924            )
925            .mount(&server)
926            .await;
927
928        // When building a client with the base server.
929        builder = builder.server_name_or_homeserver_url(server.uri());
930        let client = builder.build().await.unwrap();
931
932        // Then a client should be built with native support for sliding sync.
933        // It's native support because it's the default. Nothing is checked here.
934        assert!(client.sliding_sync_version().is_native());
935    }
936
937    #[async_test]
938    async fn test_discovery_well_known_with_sliding_sync() {
939        // Given a base server with a well-known file that points to a homeserver with a
940        // sliding sync proxy.
941        let server = MockServer::start().await;
942        let homeserver = make_mock_homeserver().await;
943        let mut builder = ClientBuilder::new();
944
945        Mock::given(method("GET"))
946            .and(path("/.well-known/matrix/client"))
947            .respond_with(ResponseTemplate::new(200).set_body_json(make_well_known_json(
948                &homeserver.uri(),
949                Some("https://localhost:1234"),
950            )))
951            .mount(&server)
952            .await;
953
954        // When building a client with the base server, with sliding sync to
955        // auto-discover the proxy.
956        builder = builder
957            .server_name_or_homeserver_url(server.uri())
958            .sliding_sync_version_builder(SlidingSyncVersionBuilder::DiscoverProxy);
959        let client = builder.build().await.unwrap();
960
961        // Then a client should be built with support for sliding sync.
962        assert_matches!(
963            client.sliding_sync_version(),
964            SlidingSyncVersion::Proxy { url } => {
965                assert_eq!(url, Url::parse("https://localhost:1234").unwrap());
966            }
967        );
968    }
969
970    #[async_test]
971    async fn test_discovery_well_known_with_sliding_sync_override() {
972        // Given a base server with a well-known file that points to a homeserver with a
973        // sliding sync proxy.
974        let server = MockServer::start().await;
975        let homeserver = make_mock_homeserver().await;
976        let mut builder = ClientBuilder::new();
977
978        Mock::given(method("GET"))
979            .and(path("/.well-known/matrix/client"))
980            .respond_with(ResponseTemplate::new(200).set_body_json(make_well_known_json(
981                &homeserver.uri(),
982                Some("https://localhost:1234"),
983            )))
984            .mount(&server)
985            .await;
986
987        // When building a client with the base server and a custom sliding sync proxy
988        // set.
989        let url = Url::parse("https://localhost:9012").unwrap();
990
991        builder = builder
992            .sliding_sync_version_builder(SlidingSyncVersionBuilder::Proxy { url: url.clone() })
993            .server_name_or_homeserver_url(server.uri());
994
995        let client = builder.build().await.unwrap();
996
997        // Then a client should be built and configured with the custom sliding sync
998        // proxy.
999        assert_matches!(
1000            client.sliding_sync_version(),
1001            SlidingSyncVersion::Proxy { url: given_url } => {
1002                assert_eq!(url, given_url);
1003            }
1004        );
1005    }
1006
1007    #[async_test]
1008    async fn test_sliding_sync_discover_proxy() {
1009        // Given a homeserver with a `.well-known` file.
1010        let homeserver = make_mock_homeserver().await;
1011        let mut builder = ClientBuilder::new();
1012
1013        let expected_url = Url::parse("https://localhost:1234").unwrap();
1014
1015        Mock::given(method("GET"))
1016            .and(path("/.well-known/matrix/client"))
1017            .respond_with(ResponseTemplate::new(200).set_body_json(make_well_known_json(
1018                &homeserver.uri(),
1019                Some(expected_url.as_str()),
1020            )))
1021            .mount(&homeserver)
1022            .await;
1023
1024        // When building the client with sliding sync to auto-discover the
1025        // proxy version.
1026        builder = builder
1027            .server_name_or_homeserver_url(homeserver.uri())
1028            .sliding_sync_version_builder(SlidingSyncVersionBuilder::DiscoverProxy);
1029
1030        let client = builder.build().await.unwrap();
1031
1032        // Then, sliding sync has the correct proxy URL.
1033        assert_matches!(
1034            client.sliding_sync_version(),
1035            SlidingSyncVersion::Proxy { url } => {
1036                assert_eq!(url, expected_url);
1037            }
1038        );
1039    }
1040
1041    #[async_test]
1042    async fn test_sliding_sync_discover_native() {
1043        // Given a homeserver with a `/versions` file.
1044        let homeserver = make_mock_homeserver().await;
1045        let mut builder = ClientBuilder::new();
1046
1047        // When building the client with sliding sync to auto-discover the
1048        // native version.
1049        builder = builder
1050            .server_name_or_homeserver_url(homeserver.uri())
1051            .sliding_sync_version_builder(SlidingSyncVersionBuilder::DiscoverNative);
1052
1053        let client = builder.build().await.unwrap();
1054
1055        // Then, sliding sync has the correct native version.
1056        assert_matches!(client.sliding_sync_version(), SlidingSyncVersion::Native);
1057    }
1058
1059    #[async_test]
1060    #[cfg(feature = "e2e-encryption")]
1061    async fn test_set_up_decryption_trust_requirement_cross_signed() {
1062        let homeserver = make_mock_homeserver().await;
1063        let builder = ClientBuilder::new()
1064            .server_name_or_homeserver_url(homeserver.uri())
1065            .with_decryption_trust_requirement(TrustRequirement::CrossSigned);
1066
1067        let client = builder.build().await.unwrap();
1068        assert_matches!(
1069            client.base_client().decryption_trust_requirement,
1070            TrustRequirement::CrossSigned
1071        );
1072    }
1073
1074    #[async_test]
1075    #[cfg(feature = "e2e-encryption")]
1076    async fn test_set_up_decryption_trust_requirement_untrusted() {
1077        let homeserver = make_mock_homeserver().await;
1078
1079        let builder = ClientBuilder::new()
1080            .server_name_or_homeserver_url(homeserver.uri())
1081            .with_decryption_trust_requirement(TrustRequirement::Untrusted);
1082
1083        let client = builder.build().await.unwrap();
1084        assert_matches!(
1085            client.base_client().decryption_trust_requirement,
1086            TrustRequirement::Untrusted
1087        );
1088    }
1089
1090    /* Helper functions */
1091
1092    async fn make_mock_homeserver() -> MockServer {
1093        let homeserver = MockServer::start().await;
1094        Mock::given(method("GET"))
1095            .and(path("/_matrix/client/versions"))
1096            .respond_with(ResponseTemplate::new(200).set_body_json(&*test_json::VERSIONS))
1097            .mount(&homeserver)
1098            .await;
1099        Mock::given(method("GET"))
1100            .and(path("/_matrix/client/r0/login"))
1101            .respond_with(ResponseTemplate::new(200).set_body_json(&*test_json::LOGIN_TYPES))
1102            .mount(&homeserver)
1103            .await;
1104        homeserver
1105    }
1106
1107    fn make_well_known_json(
1108        homeserver_url: &str,
1109        sliding_sync_proxy_url: Option<&str>,
1110    ) -> JsonValue {
1111        ::serde_json::Value::Object({
1112            let mut object = ::serde_json::Map::new();
1113            let _ = object.insert(
1114                "m.homeserver".into(),
1115                json_internal!({
1116                    "base_url": homeserver_url
1117                }),
1118            );
1119
1120            if let Some(sliding_sync_proxy_url) = sliding_sync_proxy_url {
1121                let _ = object.insert(
1122                    "org.matrix.msc3575.proxy".into(),
1123                    json_internal!({
1124                        "url": sliding_sync_proxy_url
1125                    }),
1126                );
1127            }
1128
1129            object
1130        })
1131    }
1132
1133    #[async_test]
1134    async fn test_cross_process_store_locks_holder_name() {
1135        {
1136            let homeserver = make_mock_homeserver().await;
1137            let client =
1138                ClientBuilder::new().homeserver_url(homeserver.uri()).build().await.unwrap();
1139
1140            assert_eq!(client.cross_process_store_locks_holder_name(), "main");
1141        }
1142
1143        {
1144            let homeserver = make_mock_homeserver().await;
1145            let client = ClientBuilder::new()
1146                .homeserver_url(homeserver.uri())
1147                .cross_process_store_locks_holder_name("foo".to_owned())
1148                .build()
1149                .await
1150                .unwrap();
1151
1152            assert_eq!(client.cross_process_store_locks_holder_name(), "foo");
1153        }
1154    }
1155}