Skip to main content

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