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