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::{
25    collections::BTreeSet,
26    fmt,
27    sync::{Arc, RwLock as StdRwLock},
28};
29
30#[cfg(feature = "sqlite")]
31use futures_util::try_join;
32use homeserver_config::*;
33#[cfg(feature = "e2e-encryption")]
34use matrix_sdk_base::crypto::DecryptionSettings;
35#[cfg(feature = "experimental-x509-identity-verification")]
36use matrix_sdk_base::crypto::x509::{RawX509Signer, RawX509Verifier};
37#[cfg(feature = "e2e-encryption")]
38use matrix_sdk_base::crypto::{CollectStrategy, TrustRequirement};
39use matrix_sdk_base::{
40    BaseClient, DmRoomDefinition, StateStoreDataKey, StateStoreDataValue, ThreadingSupport,
41    store::StoreConfig, ttl::TtlValue,
42};
43use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig;
44#[cfg(feature = "sqlite")]
45use matrix_sdk_sqlite::SqliteStoreConfig;
46#[cfg(not(target_family = "wasm"))]
47use reqwest::Certificate;
48use ruma::{
49    OwnedServerName, ServerName,
50    api::{MatrixVersion, SupportedVersions, error::FromHttpResponseError},
51    presence::PresenceState,
52};
53use thiserror::Error;
54#[cfg(feature = "experimental-search")]
55use tokio::sync::Mutex;
56use tokio::sync::OnceCell;
57use tracing::{Span, debug, field::debug, instrument, warn};
58
59use super::{Client, ClientInner};
60#[cfg(feature = "e2e-encryption")]
61use crate::encryption::EncryptionSettings;
62#[cfg(not(target_family = "wasm"))]
63use crate::http_client::HttpSettings;
64#[cfg(feature = "experimental-search")]
65use crate::search_index::SearchIndex;
66#[cfg(feature = "experimental-search")]
67use crate::search_index::SearchIndexStoreKind;
68use crate::{
69    HttpError, IdParseError,
70    authentication::AuthCtx,
71    client::caches::CachedValue::{Cached, NotSet},
72    config::RequestConfig,
73    error::RumaApiError,
74    http_client::HttpClient,
75    media::{DefaultMediaFetcher, MediaFetcher},
76    send_queue::SendQueueData,
77    sliding_sync::VersionBuilder as SlidingSyncVersionBuilder,
78};
79
80/// Builder that allows creating and configuring various parts of a [`Client`].
81///
82/// When setting the `StateStore` it is up to the user to open/connect the
83/// storage backend before client creation.
84///
85/// # Examples
86///
87/// ```
88/// use matrix_sdk::Client;
89/// // To pass all the request through mitmproxy set the proxy and disable SSL
90/// // verification
91///
92/// let client_builder = Client::builder()
93///     .proxy("http://localhost:8080")
94///     .disable_ssl_verification();
95/// ```
96///
97/// # Example for using a custom http client
98///
99/// Note: setting a custom http client will ignore `user_agent`, `proxy`, and
100/// `disable_ssl_verification` - you'd need to set these yourself if you want
101/// them.
102///
103/// ```
104/// use std::sync::Arc;
105///
106/// use matrix_sdk::Client;
107///
108/// // setting up a custom http client
109/// let reqwest_builder = reqwest::ClientBuilder::new()
110///     .https_only(true)
111///     .no_proxy()
112///     .user_agent("MyApp/v3.0");
113///
114/// let client_builder =
115///     Client::builder().http_client(reqwest_builder.build()?);
116/// # anyhow::Ok(())
117/// ```
118#[must_use]
119#[derive(Clone, Debug)]
120pub struct ClientBuilder {
121    homeserver_cfg: Option<HomeserverConfig>,
122    sliding_sync_version_builder: SlidingSyncVersionBuilder,
123    http_cfg: Option<HttpConfig>,
124    store_config: BuilderStoreConfig,
125    request_config: RequestConfig,
126    respect_login_well_known: bool,
127    well_known_lookup_disabled: bool,
128    server_versions: Option<BTreeSet<MatrixVersion>>,
129    handle_refresh_tokens: bool,
130    base_client: Option<BaseClient>,
131    #[cfg(feature = "e2e-encryption")]
132    encryption_settings: EncryptionSettings,
133    #[cfg(feature = "e2e-encryption")]
134    room_key_recipient_strategy: CollectStrategy,
135    #[cfg(feature = "e2e-encryption")]
136    decryption_settings: DecryptionSettings,
137    #[cfg(feature = "e2e-encryption")]
138    enable_share_history_on_invite: bool,
139    enable_automatic_back_pagination: bool,
140    enable_event_cache: bool,
141    cross_process_lock_config: CrossProcessLockConfig,
142    threading_support: ThreadingSupport,
143    #[cfg(feature = "experimental-search")]
144    search_index_store_kind: SearchIndexStoreKind,
145    #[cfg(feature = "experimental-x509-identity-verification")]
146    x509_signer: Option<Arc<dyn RawX509Signer>>,
147    #[cfg(feature = "experimental-x509-identity-verification")]
148    x509_verifier: Option<Arc<dyn RawX509Verifier>>,
149    dm_room_definition: DmRoomDefinition,
150    media_fetcher: Arc<dyn MediaFetcher>,
151}
152
153impl ClientBuilder {
154    const DEFAULT_CROSS_PROCESS_STORE_LOCKS_HOLDER_NAME: &str = "main";
155
156    pub(crate) fn new() -> Self {
157        Self {
158            homeserver_cfg: None,
159            sliding_sync_version_builder: SlidingSyncVersionBuilder::Unstable,
160            http_cfg: None,
161            store_config: BuilderStoreConfig::Custom(StoreConfig::new(
162                CrossProcessLockConfig::multi_process(
163                    Self::DEFAULT_CROSS_PROCESS_STORE_LOCKS_HOLDER_NAME,
164                ),
165            )),
166            request_config: Default::default(),
167            respect_login_well_known: true,
168            well_known_lookup_disabled: false,
169            server_versions: None,
170            handle_refresh_tokens: false,
171            base_client: None,
172            #[cfg(feature = "e2e-encryption")]
173            encryption_settings: Default::default(),
174            #[cfg(feature = "e2e-encryption")]
175            room_key_recipient_strategy: Default::default(),
176            #[cfg(feature = "e2e-encryption")]
177            decryption_settings: DecryptionSettings {
178                sender_device_trust_requirement: TrustRequirement::Untrusted,
179            },
180            #[cfg(feature = "e2e-encryption")]
181            enable_share_history_on_invite: true,
182            enable_automatic_back_pagination: false,
183            enable_event_cache: true,
184            cross_process_lock_config: CrossProcessLockConfig::MultiProcess {
185                holder_name: Self::DEFAULT_CROSS_PROCESS_STORE_LOCKS_HOLDER_NAME.to_owned(),
186            },
187            threading_support: ThreadingSupport::Disabled,
188            #[cfg(feature = "experimental-search")]
189            search_index_store_kind: SearchIndexStoreKind::InMemory,
190            #[cfg(feature = "experimental-x509-identity-verification")]
191            x509_signer: None,
192            #[cfg(feature = "experimental-x509-identity-verification")]
193            x509_verifier: None,
194            dm_room_definition: DmRoomDefinition::MatrixSpec,
195            media_fetcher: Arc::new(DefaultMediaFetcher),
196        }
197    }
198
199    /// Sets a [`MediaFetcher`] that will be used to get media from the media
200    /// server.
201    pub fn media_fetcher(mut self, media_fetcher: Arc<dyn MediaFetcher>) -> Self {
202        self.media_fetcher = media_fetcher.clone();
203        self
204    }
205
206    /// Sets the definition the [`Client`] will use to check if a room is a DM.
207    ///
208    /// By default this is [`DmRoomDefinition::MatrixSpec`].
209    pub fn dm_room_definition(mut self, dm_room_definition: DmRoomDefinition) -> Self {
210        self.dm_room_definition = dm_room_definition;
211        self
212    }
213
214    /// Set the homeserver URL to use.
215    ///
216    /// The following methods are mutually exclusive: [`Self::homeserver_url`],
217    /// [`Self::server_name`] [`Self::insecure_server_name_no_tls`],
218    /// [`Self::server_name_or_homeserver_url`]. If you set more than one, then
219    /// whatever was set last will be used.
220    ///
221    /// This is the only one of them that never performs a
222    /// `.well-known/matrix/client` lookup, so it is the one to use together
223    /// with [`Self::disable_well_known_lookup`].
224    pub fn homeserver_url(mut self, url: impl AsRef<str>) -> Self {
225        self.homeserver_cfg = Some(HomeserverConfig::HomeserverUrl(url.as_ref().to_owned()));
226        self
227    }
228
229    /// Set the server name to discover the homeserver from.
230    ///
231    /// We assume we can connect in HTTPS to that server. If that's not the
232    /// case, prefer using [`Self::insecure_server_name_no_tls`].
233    ///
234    /// The following methods are mutually exclusive: [`Self::homeserver_url`],
235    /// [`Self::server_name`] [`Self::insecure_server_name_no_tls`],
236    /// [`Self::server_name_or_homeserver_url`]. If you set more than one, then
237    /// whatever was set last will be used.
238    ///
239    /// This performs a `.well-known/matrix/client` lookup, and is therefore
240    /// incompatible with [`Self::disable_well_known_lookup`]: [`Self::build`]
241    /// then fails with [`ClientBuildError::WellKnownLookupDisabled`].
242    pub fn server_name(mut self, server_name: &ServerName) -> Self {
243        self.homeserver_cfg = Some(HomeserverConfig::ServerName {
244            server: server_name.to_owned(),
245            // Assume HTTPS if not specified.
246            protocol: UrlScheme::Https,
247        });
248        self
249    }
250
251    /// Set the server name to discover the homeserver from, assuming an HTTP
252    /// (not secured) scheme. This also relaxes OAuth 2.0 discovery checks to
253    /// allow HTTP schemes.
254    ///
255    /// The following methods are mutually exclusive: [`Self::homeserver_url`],
256    /// [`Self::server_name`] [`Self::insecure_server_name_no_tls`],
257    /// [`Self::server_name_or_homeserver_url`]. If you set more than one, then
258    /// whatever was set last will be used.
259    ///
260    /// This performs a `.well-known/matrix/client` lookup, and is therefore
261    /// incompatible with [`Self::disable_well_known_lookup`]: [`Self::build`]
262    /// then fails with [`ClientBuildError::WellKnownLookupDisabled`].
263    pub fn insecure_server_name_no_tls(mut self, server_name: &ServerName) -> Self {
264        self.homeserver_cfg = Some(HomeserverConfig::ServerName {
265            server: server_name.to_owned(),
266            protocol: UrlScheme::Http,
267        });
268        self
269    }
270
271    /// Set the server name to discover the homeserver from, falling back to
272    /// using it as a homeserver URL if discovery fails. When falling back to a
273    /// homeserver URL, a check is made to ensure that the server exists (unlike
274    /// [`Self::homeserver_url`], so you can guarantee that the client is ready
275    /// to use.
276    ///
277    /// The following methods are mutually exclusive: [`Self::homeserver_url`],
278    /// [`Self::server_name`] [`Self::insecure_server_name_no_tls`],
279    /// [`Self::server_name_or_homeserver_url`]. If you set more than one, then
280    /// whatever was set last will be used.
281    ///
282    /// With [`Self::disable_well_known_lookup`], the discovery step is skipped
283    /// and only the homeserver URL check is performed, so a homeserver URL
284    /// still works while a delegating server name fails with
285    /// [`ClientBuildError::InvalidServerName`].
286    pub fn server_name_or_homeserver_url(mut self, server_name_or_url: impl AsRef<str>) -> Self {
287        self.homeserver_cfg = Some(HomeserverConfig::ServerNameOrHomeserverUrl(
288            server_name_or_url.as_ref().to_owned(),
289        ));
290        self
291    }
292
293    /// Set sliding sync to a specific version.
294    pub fn sliding_sync_version_builder(
295        mut self,
296        version_builder: SlidingSyncVersionBuilder,
297    ) -> Self {
298        self.sliding_sync_version_builder = version_builder;
299        self
300    }
301
302    /// Set up the store configuration for an SQLite store.
303    #[cfg(feature = "sqlite")]
304    pub fn sqlite_store(mut self, path: impl AsRef<Path>, passphrase: Option<&str>) -> Self {
305        let sqlite_store_config = SqliteStoreConfig::new(path).passphrase(passphrase);
306        self.store_config =
307            BuilderStoreConfig::Sqlite { config: sqlite_store_config, cache_path: None };
308
309        self
310    }
311
312    /// Set up the store configuration for an SQLite store with cached data
313    /// separated out from state/crypto data.
314    #[cfg(feature = "sqlite")]
315    pub fn sqlite_store_with_cache_path(
316        mut self,
317        path: impl AsRef<Path>,
318        cache_path: impl AsRef<Path>,
319        passphrase: Option<&str>,
320    ) -> Self {
321        let sqlite_store_config = SqliteStoreConfig::new(path).passphrase(passphrase);
322        self.store_config = BuilderStoreConfig::Sqlite {
323            config: sqlite_store_config,
324            cache_path: Some(cache_path.as_ref().to_owned()),
325        };
326
327        self
328    }
329
330    /// Set up the store configuration for an SQLite store with a store config,
331    /// and with an optional cache data separated out from state/crypto data.
332    #[cfg(feature = "sqlite")]
333    pub fn sqlite_store_with_config_and_cache_path(
334        mut self,
335        config: SqliteStoreConfig,
336        cache_path: Option<impl AsRef<Path>>,
337    ) -> Self {
338        self.store_config = BuilderStoreConfig::Sqlite {
339            config,
340            cache_path: cache_path.map(|cache_path| cache_path.as_ref().to_owned()),
341        };
342
343        self
344    }
345
346    /// Set up the store configuration for a IndexedDB store.
347    #[cfg(feature = "indexeddb")]
348    pub fn indexeddb_store(mut self, name: &str, passphrase: Option<&str>) -> Self {
349        self.store_config = BuilderStoreConfig::IndexedDb {
350            name: name.to_owned(),
351            passphrase: passphrase.map(ToOwned::to_owned),
352        };
353        self
354    }
355
356    /// Set up the store configuration.
357    ///
358    /// The easiest way to get a [`StoreConfig`] is to use the
359    /// `make_store_config` method from one of the store crates.
360    ///
361    /// # Arguments
362    ///
363    /// - `store_config` - The configuration of the store.
364    ///
365    /// # Examples
366    ///
367    /// ```
368    /// # use matrix_sdk_base::store::MemoryStore;
369    /// # use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig;
370    /// # let custom_state_store = MemoryStore::new();
371    /// use matrix_sdk::{Client, config::StoreConfig};
372    ///
373    /// let store_config = StoreConfig::new(CrossProcessLockConfig::MultiProcess {
374    ///     holder_name: "cross-process-store-locks-holder-name".to_owned(),
375    /// })
376    /// .state_store(custom_state_store);
377    /// let client_builder = Client::builder().store_config(store_config);
378    /// ```
379    pub fn store_config(mut self, store_config: StoreConfig) -> Self {
380        self.store_config = BuilderStoreConfig::Custom(store_config);
381        self
382    }
383
384    /// Update the client's homeserver URL with the discovery information
385    /// present in the login response, if any.
386    pub fn respect_login_well_known(mut self, value: bool) -> Self {
387        self.respect_login_well_known = value;
388        self
389    }
390
391    /// Disable all the `/.well-known/matrix/client` lookups, both the one
392    /// performed by [`Self::build`] to discover the homeserver, and all the
393    /// ones performed later by the built [`Client`].
394    ///
395    /// Some deployments must not emit any request to the well-known URI of
396    /// their domain. When disabled, [`Client::tile_server`] returns `None`,
397    /// [`Client::well_known_rtc_transports`] returns an empty list, and
398    /// [`Client::discover_rtc_transports`] doesn't fall back to the well-known
399    /// `m.rtc_foci`, relying only on the MSC4143 discovery endpoint.
400    ///
401    /// # Interaction with the homeserver setters
402    ///
403    /// The homeserver must then be resolvable without a well-known lookup:
404    ///
405    /// - [`Self::homeserver_url`] works, and is the recommended choice.
406    /// - [`Self::server_name`] and [`Self::insecure_server_name_no_tls`] can
407    ///   _only_ be resolved through the well-known, so [`Self::build`] fails
408    ///   with [`ClientBuildError::WellKnownLookupDisabled`]. Assuming that the
409    ///   server name is also the homeserver would silently talk to the wrong
410    ///   host for any deployment that delegates.
411    /// - [`Self::server_name_or_homeserver_url`] skips the well-known step and
412    ///   goes straight to checking whether the value points at a homeserver, so
413    ///   it works when given a homeserver URL, and fails with
414    ///   [`ClientBuildError::InvalidServerName`] otherwise.
415    ///
416    /// [`Client::discover_rtc_transports`]: crate::Client::discover_rtc_transports
417    /// [`Client::tile_server`]: crate::Client::tile_server
418    /// [`Client::well_known_rtc_transports`]: crate::Client::well_known_rtc_transports
419    pub fn disable_well_known_lookup(mut self, disable: bool) -> Self {
420        self.well_known_lookup_disabled = disable;
421        self
422    }
423
424    /// Set the default timeout, fail and retry behavior for all HTTP requests.
425    pub fn request_config(mut self, request_config: RequestConfig) -> Self {
426        self.request_config = request_config;
427        self
428    }
429
430    /// Set the proxy through which all the HTTP requests should go.
431    ///
432    /// Note, only HTTP proxies are supported.
433    ///
434    /// # Arguments
435    ///
436    /// - `proxy` - The HTTP URL of the proxy.
437    ///
438    /// # Examples
439    ///
440    /// ```no_run
441    /// use matrix_sdk::Client;
442    ///
443    /// let client_config = Client::builder().proxy("http://localhost:8080");
444    /// ```
445    #[cfg(not(target_family = "wasm"))]
446    pub fn proxy(mut self, proxy: impl AsRef<str>) -> Self {
447        self.http_settings().proxy = Some(proxy.as_ref().to_owned());
448        self
449    }
450
451    /// Disable SSL verification for the HTTP requests.
452    #[cfg(not(target_family = "wasm"))]
453    pub fn disable_ssl_verification(mut self) -> Self {
454        self.http_settings().disable_ssl_verification = true;
455        self
456    }
457
458    /// Set a custom HTTP user agent for the client.
459    #[cfg(not(target_family = "wasm"))]
460    pub fn user_agent(mut self, user_agent: impl AsRef<str>) -> Self {
461        self.http_settings().user_agent = Some(user_agent.as_ref().to_owned());
462        self
463    }
464
465    /// Add the given list of certificates to the certificate store of the HTTP
466    /// client.
467    ///
468    /// These additional certificates will be trusted and considered when
469    /// establishing a HTTP request.
470    ///
471    /// Internally this will call the
472    /// [`reqwest::ClientBuilder::add_root_certificate()`] method.
473    #[cfg(not(target_family = "wasm"))]
474    pub fn add_root_certificates(mut self, certificates: Vec<Certificate>) -> Self {
475        self.http_settings().additional_root_certificates = certificates;
476        self
477    }
478
479    /// Don't trust any system root certificates, only trust the certificates
480    /// provided through
481    /// [`add_root_certificates`][ClientBuilder::add_root_certificates].
482    #[cfg(not(target_family = "wasm"))]
483    pub fn disable_built_in_root_certificates(mut self) -> Self {
484        self.http_settings().disable_built_in_root_certificates = true;
485        self
486    }
487
488    /// Specify a [`reqwest::Client`] instance to handle sending requests and
489    /// receiving responses.
490    ///
491    /// This method is mutually exclusive with
492    /// [`proxy()`][ClientBuilder::proxy],
493    /// [`disable_ssl_verification`][ClientBuilder::disable_ssl_verification],
494    /// [`add_root_certificates`][ClientBuilder::add_root_certificates],
495    /// [`disable_built_in_root_certificates`][ClientBuilder::disable_built_in_root_certificates],
496    /// and [`user_agent()`][ClientBuilder::user_agent].
497    pub fn http_client(mut self, client: reqwest::Client) -> Self {
498        self.http_cfg = Some(HttpConfig::Custom(client));
499        self
500    }
501
502    /// Specify the Matrix versions supported by the homeserver manually, rather
503    /// than `build()` doing it using a `get_supported_versions` request.
504    ///
505    /// This is helpful for test code that doesn't care to mock that endpoint.
506    pub fn server_versions(mut self, value: impl IntoIterator<Item = MatrixVersion>) -> Self {
507        self.server_versions = Some(value.into_iter().collect());
508        self
509    }
510
511    #[cfg(not(target_family = "wasm"))]
512    fn http_settings(&mut self) -> &mut HttpSettings {
513        self.http_cfg.get_or_insert_with(Default::default).settings()
514    }
515
516    /// Handle [refreshing access tokens] automatically.
517    ///
518    /// By default, the `Client` forwards any error and doesn't handle errors
519    /// with the access token, which means that
520    /// [`Client::refresh_access_token()`] needs to be called manually to
521    /// refresh access tokens.
522    ///
523    /// Enabling this setting means that the `Client` will try to refresh the
524    /// token automatically, which means that:
525    ///
526    /// - If refreshing the token fails, the error is forwarded, so any endpoint
527    ///   can return [`HttpError::RefreshToken`]. If an [`UnknownToken`] error
528    ///   is encountered, it means that the user needs to be logged in again.
529    ///
530    /// - The access token and refresh token need to be watched for changes,
531    ///   using the authentication API's `session_tokens_stream()` for example,
532    ///   to be able to [restore the session] later.
533    ///
534    /// [refreshing access tokens]: https://spec.matrix.org/v1.3/client-server-api/#refreshing-access-tokens
535    /// [`UnknownToken`]: ruma::api::error::ErrorKind::UnknownToken
536    /// [restore the session]: Client::restore_session
537    pub fn handle_refresh_tokens(mut self) -> Self {
538        self.handle_refresh_tokens = true;
539        self
540    }
541
542    /// Public for test only
543    #[doc(hidden)]
544    pub fn base_client(mut self, base_client: BaseClient) -> Self {
545        self.base_client = Some(base_client);
546        self
547    }
548
549    /// Enables specific encryption settings that will persist throughout the
550    /// entire lifetime of the `Client`.
551    #[cfg(feature = "e2e-encryption")]
552    pub fn with_encryption_settings(mut self, settings: EncryptionSettings) -> Self {
553        self.encryption_settings = settings;
554        self
555    }
556
557    /// Set the strategy to be used for picking recipient devices, when sending
558    /// an encrypted message.
559    #[cfg(feature = "e2e-encryption")]
560    pub fn with_room_key_recipient_strategy(mut self, strategy: CollectStrategy) -> Self {
561        self.room_key_recipient_strategy = strategy;
562        self
563    }
564
565    /// Set the trust requirement to be used when decrypting events.
566    #[cfg(feature = "e2e-encryption")]
567    pub fn with_decryption_settings(mut self, decryption_settings: DecryptionSettings) -> Self {
568        self.decryption_settings = decryption_settings;
569        self
570    }
571
572    /// Whether to enable the experimental support for sending and receiving
573    /// encrypted room history on invite, per [MSC4268].
574    ///
575    /// This setting is now enabled by default, but can be disabled via this
576    /// method.
577    ///
578    /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
579    #[cfg(feature = "e2e-encryption")]
580    pub fn with_enable_share_history_on_invite(
581        mut self,
582        enable_share_history_on_invite: bool,
583    ) -> Self {
584        self.enable_share_history_on_invite = enable_share_history_on_invite;
585        self
586    }
587
588    /// Whether to automatically back-paginate a room's history in the
589    /// background, under certain conditions (search backfill, latest-event
590    /// resolution, read-receipt finding).
591    ///
592    /// Off by default.
593    pub fn with_enable_automatic_back_pagination(mut self, enable: bool) -> Self {
594        self.enable_automatic_back_pagination = enable;
595        self
596    }
597
598    /// Whether to enable the [`EventCache`], and the [`LatestEvents`] which
599    /// depend on it.
600    ///
601    /// When enabled, the [`EventCache`] handles all sync updates starts the
602    /// redecryptor, broadcasts updates to the `LatestEvents` or
603    /// `matrix-sdk-search` API, and so on. Not all Clients might be interested
604    /// by this feature, e.g. a notification service extensions.
605    ///
606    /// On by default.
607    ///
608    /// [`EventCache`]: crate::event_cache::EventCache
609    /// [`LatestEvents`]: crate::latest_events::LatestEvents
610    pub fn with_event_cache(mut self, enable: bool) -> Self {
611        self.enable_event_cache = enable;
612        self
613    }
614
615    /// Set the cross-process store locks holder name.
616    ///
617    /// The SDK provides cross-process store locks (see
618    /// [`matrix_sdk_common::cross_process_lock::CrossProcessLock`]). The
619    /// `holder_name` will be the value used for all cross-process store locks
620    /// used by the `Client` being built.
621    ///
622    /// If 2 concurrent `Client`s are running in 2 different process, this
623    /// method must be called with different `hold_name` values.
624    pub fn cross_process_store_config(
625        mut self,
626        cross_process_store_config: CrossProcessLockConfig,
627    ) -> Self {
628        self.cross_process_lock_config = cross_process_store_config;
629        self
630    }
631
632    /// Whether the threads feature is enabled throuoghout the SDK. This will
633    /// affect how timelines are setup, how read receipts are sent and how room
634    /// unreads are computed.
635    pub fn with_threading_support(mut self, threading_support: ThreadingSupport) -> Self {
636        self.threading_support = threading_support;
637        self
638    }
639
640    /// The base directory in which each room's index directory will be stored.
641    #[cfg(feature = "experimental-search")]
642    pub fn search_index_store(mut self, kind: SearchIndexStoreKind) -> Self {
643        self.search_index_store_kind = kind;
644        self
645    }
646
647    /// The signer we will use to sign master signing keys and outgoing secret
648    /// requests.
649    #[cfg(feature = "experimental-x509-identity-verification")]
650    pub fn with_x509_signer(mut self, x509_signer: Option<Arc<dyn RawX509Signer>>) -> Self {
651        self.x509_signer = x509_signer;
652        self
653    }
654
655    /// The verifier we will use to verify master signing keys and incoming
656    /// secret requests.
657    #[cfg(feature = "experimental-x509-identity-verification")]
658    pub fn with_x509_verifier(mut self, x509_verifier: Option<Arc<dyn RawX509Verifier>>) -> Self {
659        self.x509_verifier = x509_verifier;
660        self
661    }
662
663    /// Create a [`Client`] with the options set on this builder.
664    ///
665    /// # Errors
666    ///
667    /// This method can fail for two general reasons:
668    ///
669    /// - Invalid input: a missing or invalid homeserver URL or invalid proxy
670    ///   URL
671    /// - HTTP error: If you supplied a user ID instead of a homeserver URL, a
672    ///   server discovery request is made which can fail; if you didn't set
673    ///   [`server_versions(false)`][Self::server_versions], that amounts to
674    ///   another request that can fail
675    #[instrument(skip_all, target = "matrix_sdk::client", fields(homeserver))]
676    pub async fn build(self) -> Result<Client, ClientBuildError> {
677        debug!("Starting to build the Client");
678
679        let homeserver_cfg = self.homeserver_cfg.ok_or(ClientBuildError::MissingHomeserver)?;
680        Span::current().record("homeserver", debug(&homeserver_cfg));
681
682        let base_client = if let Some(base_client) = self.base_client {
683            base_client
684        } else {
685            #[allow(unused_mut)]
686            let mut client = BaseClient::new(
687                build_store_config(self.store_config, &self.cross_process_lock_config).await?,
688                self.threading_support,
689                self.dm_room_definition,
690            );
691
692            #[cfg(feature = "e2e-encryption")]
693            {
694                client.room_key_recipient_strategy = self.room_key_recipient_strategy;
695                client.decryption_settings = self.decryption_settings;
696            }
697
698            #[cfg(feature = "experimental-x509-identity-verification")]
699            client.set_x509_signer(self.x509_signer);
700            #[cfg(feature = "experimental-x509-identity-verification")]
701            client.set_x509_verifier(self.x509_verifier);
702
703            client
704        };
705
706        let http_client = HttpClient::new(
707            #[cfg_attr(target_family = "wasm", allow(clippy::infallible_destructuring_match))]
708            match self.http_cfg.unwrap_or_default() {
709                #[cfg(not(target_family = "wasm"))]
710                HttpConfig::Settings(mut settings) => {
711                    settings.apply_timeouts(&self.request_config);
712                    settings.make_client()?
713                }
714                HttpConfig::Custom(c) => c,
715            },
716            self.request_config,
717        );
718
719        #[allow(unused_variables)]
720        let HomeserverDiscoveryResult { server, homeserver, supported_versions, well_known } =
721            homeserver_cfg.discover(&http_client, self.well_known_lookup_disabled).await?;
722
723        let sliding_sync_version = {
724            let supported_versions = match supported_versions {
725                Some(versions) => Some(versions),
726                None if self.sliding_sync_version_builder.needs_get_supported_versions() => {
727                    Some(get_supported_versions(&homeserver, &http_client).await?)
728                }
729                None => None,
730            };
731
732            let version = self.sliding_sync_version_builder.build(
733                supported_versions.map(|response| response.as_supported_versions()).as_ref(),
734            )?;
735
736            tracing::info!(?version, "selected sliding sync version");
737
738            version
739        };
740
741        let allow_insecure_oauth = homeserver.scheme() == "http";
742        let auth_ctx = Arc::new(AuthCtx::new(self.handle_refresh_tokens, allow_insecure_oauth));
743
744        // Enable the send queue by default.
745        let send_queue = Arc::new(SendQueueData::new(true));
746
747        let supported_versions = match self.server_versions {
748            Some(versions) => Cached(TtlValue::without_expiry(SupportedVersions {
749                versions,
750                features: Default::default(),
751            })),
752            None => NotSet,
753        };
754        let well_known = match well_known {
755            Some(well_known) => Cached(TtlValue::new(Some(well_known.into()))),
756            None => NotSet,
757        };
758
759        // Load the persisted retention configuration, so it's available even
760        // without connectivity.
761        let retention_configuration = match base_client
762            .state_store()
763            .get_kv_data(StateStoreDataKey::RetentionConfiguration)
764            .await
765        {
766            Ok(value) => value
767                .and_then(StateStoreDataValue::into_retention_configuration)
768                .map(|value| value.map(Into::into)),
769            Err(error) => {
770                warn!("error when loading the persisted retention configuration: {error}");
771                None
772            }
773        };
774
775        let thread_subscriptions_catchup = OnceCell::new();
776
777        #[cfg(feature = "experimental-search")]
778        let search_index =
779            SearchIndex::new(Arc::new(Mutex::new(HashMap::new())), self.search_index_store_kind);
780
781        let inner = ClientInner::new(
782            auth_ctx,
783            server,
784            homeserver,
785            sliding_sync_version,
786            Arc::new(StdRwLock::new(PresenceState::Online)),
787            http_client,
788            base_client,
789            supported_versions,
790            well_known,
791            retention_configuration,
792            self.respect_login_well_known,
793            self.well_known_lookup_disabled,
794            self.enable_automatic_back_pagination,
795            self.enable_event_cache,
796            send_queue,
797            #[cfg(feature = "e2e-encryption")]
798            self.encryption_settings,
799            #[cfg(feature = "e2e-encryption")]
800            self.enable_share_history_on_invite,
801            self.cross_process_lock_config,
802            #[cfg(feature = "experimental-search")]
803            search_index,
804            thread_subscriptions_catchup,
805            self.media_fetcher.clone(),
806        )
807        .await;
808
809        debug!("Done building the Client");
810
811        Ok(Client { inner })
812    }
813}
814
815/// Creates a server name from a user supplied string. The string is first
816/// sanitized by removing whitespace, the http(s) scheme and any trailing
817/// slashes before being parsed.
818pub fn sanitize_server_name(s: &str) -> crate::Result<OwnedServerName, IdParseError> {
819    ServerName::parse(
820        s.trim().trim_start_matches("http://").trim_start_matches("https://").trim_end_matches('/'),
821    )
822}
823
824#[allow(clippy::unused_async, unused)] // False positive when building with !sqlite & !indexeddb
825async fn build_store_config(
826    builder_config: BuilderStoreConfig,
827    cross_process_store_config: &CrossProcessLockConfig,
828) -> Result<StoreConfig, ClientBuildError> {
829    #[allow(clippy::infallible_destructuring_match)]
830    let store_config = match builder_config {
831        #[cfg(feature = "sqlite")]
832        BuilderStoreConfig::Sqlite { config, cache_path } => {
833            let config_with_cache_path = if let Some(ref cache_path) = cache_path {
834                config.clone().path(cache_path)
835            } else {
836                config.clone()
837            };
838
839            #[cfg(feature = "e2e-encryption")]
840            let (state_store, event_cache_store, media_store, crypto_store) = try_join!(
841                matrix_sdk_sqlite::SqliteStateStore::open_with_config(&config),
842                matrix_sdk_sqlite::SqliteEventCacheStore::open_with_config(&config_with_cache_path),
843                matrix_sdk_sqlite::SqliteMediaStore::open_with_config(&config_with_cache_path),
844                matrix_sdk_sqlite::SqliteCryptoStore::open_with_config(&config),
845            )?;
846            #[cfg(not(feature = "e2e-encryption"))]
847            let (state_store, event_cache_store, media_store) = try_join!(
848                matrix_sdk_sqlite::SqliteStateStore::open_with_config(&config),
849                matrix_sdk_sqlite::SqliteEventCacheStore::open_with_config(&config_with_cache_path),
850                matrix_sdk_sqlite::SqliteMediaStore::open_with_config(&config),
851            )?;
852            let store_config = StoreConfig::new(cross_process_store_config.clone())
853                .state_store(state_store)
854                .event_cache_store(event_cache_store)
855                .media_store(media_store);
856
857            #[cfg(feature = "e2e-encryption")]
858            let store_config = store_config.crypto_store(crypto_store);
859
860            store_config
861        }
862
863        #[cfg(feature = "indexeddb")]
864        BuilderStoreConfig::IndexedDb { name, passphrase } => {
865            build_indexeddb_store_config(
866                &name,
867                passphrase.as_deref(),
868                cross_process_store_config.clone(),
869            )
870            .await?
871        }
872
873        BuilderStoreConfig::Custom(config) => config,
874    };
875    Ok(store_config)
876}
877
878// The indexeddb stores only implement `IntoStateStore` and `IntoCryptoStore` on
879// wasm32, so this only compiles there.
880#[cfg(all(target_family = "wasm", feature = "indexeddb"))]
881async fn build_indexeddb_store_config(
882    name: &str,
883    passphrase: Option<&str>,
884    cross_process_store_config: CrossProcessLockConfig,
885) -> Result<StoreConfig, ClientBuildError> {
886    let stores = matrix_sdk_indexeddb::IndexeddbStores::open(name, passphrase).await?;
887    let store_config = StoreConfig::new(cross_process_store_config)
888        .state_store(stores.state)
889        .event_cache_store(stores.event_cache)
890        .media_store(stores.media);
891
892    #[cfg(feature = "e2e-encryption")]
893    let store_config = store_config.crypto_store(stores.crypto);
894
895    Ok(store_config)
896}
897
898#[cfg(all(not(target_family = "wasm"), feature = "indexeddb"))]
899#[allow(clippy::unused_async)]
900async fn build_indexeddb_store_config(
901    _name: &str,
902    _passphrase: Option<&str>,
903    _cross_process_store_config: CrossProcessLockConfig,
904) -> Result<StoreConfig, ClientBuildError> {
905    panic!("the IndexedDB is only available on the 'wasm32' arch")
906}
907
908#[derive(Clone, Debug)]
909enum HttpConfig {
910    #[cfg(not(target_family = "wasm"))]
911    Settings(HttpSettings),
912    Custom(reqwest::Client),
913}
914
915#[cfg(not(target_family = "wasm"))]
916impl HttpConfig {
917    fn settings(&mut self) -> &mut HttpSettings {
918        match self {
919            Self::Settings(s) => s,
920            Self::Custom(_) => {
921                *self = Self::default();
922                match self {
923                    Self::Settings(s) => s,
924                    Self::Custom(_) => unreachable!(),
925                }
926            }
927        }
928    }
929}
930
931impl Default for HttpConfig {
932    fn default() -> Self {
933        #[cfg(not(target_family = "wasm"))]
934        return Self::Settings(HttpSettings::default());
935
936        #[cfg(target_family = "wasm")]
937        return Self::Custom(reqwest::Client::new());
938    }
939}
940
941#[derive(Clone)]
942enum BuilderStoreConfig {
943    #[cfg(feature = "sqlite")]
944    Sqlite {
945        config: SqliteStoreConfig,
946        cache_path: Option<PathBuf>,
947    },
948    #[cfg(feature = "indexeddb")]
949    IndexedDb {
950        name: String,
951        passphrase: Option<String>,
952    },
953    Custom(StoreConfig),
954}
955
956#[cfg(not(tarpaulin_include))]
957impl fmt::Debug for BuilderStoreConfig {
958    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
959        #[allow(clippy::infallible_destructuring_match)]
960        match self {
961            #[cfg(feature = "sqlite")]
962            Self::Sqlite { config, cache_path, .. } => f
963                .debug_struct("Sqlite")
964                .field("config", config)
965                .field("cache_path", cache_path)
966                .finish_non_exhaustive(),
967
968            #[cfg(feature = "indexeddb")]
969            Self::IndexedDb { name, .. } => {
970                f.debug_struct("IndexedDb").field("name", name).finish_non_exhaustive()
971            }
972
973            Self::Custom(store_config) => f.debug_tuple("Custom").field(store_config).finish(),
974        }
975    }
976}
977
978/// Errors that can happen in [`ClientBuilder::build`].
979#[derive(Debug, Error)]
980pub enum ClientBuildError {
981    /// No homeserver or user ID was configured
982    #[error("No homeserver or user ID was configured")]
983    MissingHomeserver,
984
985    /// The supplied server name was invalid.
986    #[error("The supplied server name is invalid")]
987    InvalidServerName,
988
989    /// Resolving the homeserver requires a `.well-known/matrix/client` lookup,
990    /// but those were disabled with
991    /// [`ClientBuilder::disable_well_known_lookup`].
992    #[error(
993        "Homeserver discovery requires a .well-known lookup, which was disabled; \
994         use `ClientBuilder::homeserver_url` instead"
995    )]
996    WellKnownLookupDisabled,
997
998    /// Error looking up the .well-known endpoint on auto-discovery
999    #[error("Error looking up the .well-known endpoint on auto-discovery")]
1000    AutoDiscovery(Box<FromHttpResponseError<RumaApiError>>),
1001
1002    /// Error when building the sliding sync version.
1003    #[error(transparent)]
1004    SlidingSyncVersion(#[from] crate::sliding_sync::VersionBuilderError),
1005
1006    /// An error encountered when trying to parse the homeserver url.
1007    #[error(transparent)]
1008    Url(#[from] url::ParseError),
1009
1010    /// Error doing an HTTP request.
1011    #[error(transparent)]
1012    Http(#[from] HttpError),
1013
1014    /// Error opening the indexeddb store.
1015    #[cfg(feature = "indexeddb")]
1016    #[error(transparent)]
1017    IndexeddbStore(#[from] matrix_sdk_indexeddb::OpenStoreError),
1018
1019    /// Error opening the sqlite store.
1020    #[cfg(feature = "sqlite")]
1021    #[error(transparent)]
1022    SqliteStore(#[from] matrix_sdk_sqlite::OpenStoreError),
1023}
1024
1025// The http mocking library is not supported for wasm32
1026#[cfg(all(test, not(target_family = "wasm")))]
1027pub(crate) mod tests {
1028    use std::{future, iter, net::SocketAddr, sync::Mutex as StdMutex};
1029
1030    use assert_matches::assert_matches;
1031    use matrix_sdk_test::{async_test, test_json};
1032    use reqwest::dns::{Addrs, Name, Resolve, Resolving};
1033    use serde_json::{Value as JsonValue, json_internal};
1034    use strass::assert_let;
1035    use url::Url;
1036    use wiremock::{
1037        Mock, MockServer, ResponseTemplate,
1038        matchers::{header, method, path},
1039    };
1040
1041    use super::*;
1042    use crate::sliding_sync::Version as SlidingSyncVersion;
1043
1044    #[test]
1045    fn test_sanitize_server_name() {
1046        assert_eq!(sanitize_server_name("matrix.org").unwrap().as_str(), "matrix.org");
1047        assert_eq!(sanitize_server_name("https://matrix.org").unwrap().as_str(), "matrix.org");
1048        assert_eq!(sanitize_server_name("http://matrix.org").unwrap().as_str(), "matrix.org");
1049        assert_eq!(
1050            sanitize_server_name("https://matrix.server.org").unwrap().as_str(),
1051            "matrix.server.org"
1052        );
1053        assert_eq!(
1054            sanitize_server_name("https://matrix.server.org/").unwrap().as_str(),
1055            "matrix.server.org"
1056        );
1057        assert_eq!(
1058            sanitize_server_name("  https://matrix.server.org// ").unwrap().as_str(),
1059            "matrix.server.org"
1060        );
1061        assert_matches!(sanitize_server_name("https://matrix.server.org/something"), Err(_))
1062    }
1063
1064    // Note: Due to a limitation of the http mocking library the following tests
1065    // all supply an http:// url, to `server_name_or_homeserver_url` rather than
1066    // the plain server name, otherwise the builder will prepend https:// and
1067    // the request will fail. In practice, this isn't a problem as the builder
1068    // first strips the scheme and then checks if the name is a valid server
1069    // name, so it is a close enough approximation.
1070
1071    #[async_test]
1072    async fn test_discovery_invalid_server() {
1073        // Given a new client builder.
1074        let mut builder = ClientBuilder::new();
1075
1076        // When building a client with an invalid server name.
1077        builder = builder.server_name_or_homeserver_url("⚠️ This won't work 🚫");
1078        let error = builder.build().await.unwrap_err();
1079
1080        // Then the operation should fail due to the invalid server name.
1081        assert_matches!(error, ClientBuildError::InvalidServerName);
1082    }
1083
1084    #[async_test]
1085    async fn test_discovery_no_server() {
1086        // Given a new client builder.
1087        let mut builder = ClientBuilder::new();
1088
1089        // When building a client with a valid server name that doesn't exist.
1090        builder = builder.server_name_or_homeserver_url("localhost:3456");
1091        let error = builder.build().await.unwrap_err();
1092
1093        // Then the operation should fail with an HTTP error.
1094        println!("{error}");
1095        assert_matches!(error, ClientBuildError::Http(_));
1096    }
1097
1098    #[async_test]
1099    async fn test_discovery_web_server() {
1100        // Given a random web server that isn't a Matrix homeserver or hosting
1101        // the well-known file for one.
1102        let server = MockServer::start().await;
1103        let mut builder = ClientBuilder::new();
1104
1105        // When building a client with the server's URL.
1106        builder = builder.server_name_or_homeserver_url(server.uri());
1107        let error = builder.build().await.unwrap_err();
1108
1109        // Then the operation should fail with a server discovery error.
1110        assert_let!(ClientBuildError::AutoDiscovery(e) = error);
1111        assert_matches!(*e, FromHttpResponseError::Server(_));
1112    }
1113
1114    #[async_test]
1115    async fn test_discovery_direct_legacy() {
1116        // Given a homeserver without a well-known file.
1117        let homeserver = make_mock_homeserver().await;
1118        let mut builder = ClientBuilder::new();
1119
1120        // When building a client with the server's URL.
1121        builder = builder.server_name_or_homeserver_url(homeserver.uri());
1122        let _client = builder.build().await.unwrap();
1123
1124        // Then a client should be built with unstable support for sliding sync.
1125        assert!(_client.sliding_sync_version().is_unstable());
1126    }
1127
1128    #[async_test]
1129    async fn test_discovery_well_known_parse_error() {
1130        // Given a base server with a well-known file that has errors.
1131        let server = MockServer::start().await;
1132        let homeserver = make_mock_homeserver().await;
1133        let mut builder = ClientBuilder::new();
1134
1135        let well_known = make_well_known_json(&homeserver.uri());
1136        let bad_json = well_known.to_string().replace(',', "");
1137        Mock::given(method("GET"))
1138            .and(path("/.well-known/matrix/client"))
1139            .respond_with(ResponseTemplate::new(200).set_body_json(bad_json))
1140            .mount(&server)
1141            .await;
1142
1143        // When building a client with the base server.
1144        builder = builder.server_name_or_homeserver_url(server.uri());
1145        let error = builder.build().await.unwrap_err();
1146
1147        // Then the operation should fail due to the well-known file's contents.
1148        assert_let!(ClientBuildError::AutoDiscovery(e) = error);
1149        assert_matches!(*e, FromHttpResponseError::Deserialization(_));
1150    }
1151
1152    #[async_test]
1153    async fn test_discovery_well_known_legacy() {
1154        // Given a base server with a well-known file that points to a
1155        // homeserver that doesn't support sliding sync.
1156        let server = MockServer::start().await;
1157        let homeserver = make_mock_homeserver().await;
1158        let mut builder = ClientBuilder::new();
1159
1160        Mock::given(method("GET"))
1161            .and(path("/.well-known/matrix/client"))
1162            .respond_with(
1163                ResponseTemplate::new(200).set_body_json(make_well_known_json(&homeserver.uri())),
1164            )
1165            .mount(&server)
1166            .await;
1167
1168        // When building a client with the base server.
1169        builder = builder.server_name_or_homeserver_url(server.uri());
1170        let client = builder.build().await.unwrap();
1171
1172        // Then a client should be built with unstable support for sliding sync.
1173        // It's unstable support because it's the default. Nothing is checked
1174        // here.
1175        assert!(client.sliding_sync_version().is_unstable());
1176    }
1177
1178    #[async_test]
1179    async fn test_discovery_server_name_with_well_known_lookup_disabled() {
1180        // Given a new client builder configured with a server name only.
1181        let builder = ClientBuilder::new()
1182            .server_name(&ServerName::parse("example.org").unwrap())
1183            .disable_well_known_lookup(true);
1184
1185        // When building it. Note that no mock server is involved: the whole
1186        // point is that not a single request is made.
1187        let error = builder.build().await.unwrap_err();
1188
1189        // Then the operation should fail, rather than assume that the server
1190        // name is also the homeserver.
1191        assert_matches!(error, ClientBuildError::WellKnownLookupDisabled);
1192
1193        // And the same goes for its insecure counterpart.
1194        let error = ClientBuilder::new()
1195            .insecure_server_name_no_tls(&ServerName::parse("example.org").unwrap())
1196            .disable_well_known_lookup(true)
1197            .build()
1198            .await
1199            .unwrap_err();
1200
1201        assert_matches!(error, ClientBuildError::WellKnownLookupDisabled);
1202    }
1203
1204    #[async_test]
1205    async fn test_discovery_server_name_or_url_with_well_known_lookup_disabled() {
1206        // Given a homeserver that also serves a well-known file, which must
1207        // never be requested. `MockServer` verifies the expectation when it is
1208        // dropped.
1209        let homeserver = make_mock_homeserver().await;
1210        Mock::given(method("GET"))
1211            .and(path("/.well-known/matrix/client"))
1212            .respond_with(
1213                ResponseTemplate::new(200).set_body_json(make_well_known_json(&homeserver.uri())),
1214            )
1215            .named("well-known mock")
1216            .expect(0)
1217            .mount(&homeserver)
1218            .await;
1219
1220        // When building a client with its URL.
1221        let client = ClientBuilder::new()
1222            .server_name_or_homeserver_url(homeserver.uri())
1223            .disable_well_known_lookup(true)
1224            .build()
1225            .await
1226            .unwrap();
1227
1228        // Then the homeserver should have been resolved through the
1229        // `/_matrix/client/versions` check alone.
1230        assert_eq!(client.homeserver().as_str().trim_end_matches('/'), homeserver.uri());
1231    }
1232
1233    #[async_test]
1234    async fn test_homeserver_url_never_contacts_the_server_name() {
1235        // Given a deployment where the server name serves a well-known that
1236        // points to the underlying homeserver (hosted on an unrelated domain in
1237        // this test).
1238        let mock_server = MockServer::start().await;
1239        let address = *mock_server.address();
1240        let port = address.port();
1241        let server_name = format!("servername.com:{port}");
1242        let homeserver_name = format!("matrix.server.com:{port}");
1243
1244        // Every host is resolved to the mock server and recorded.
1245        let resolver = Arc::new(RecordingResolver { address, hosts: StdMutex::new(Vec::new()) });
1246        let http_client =
1247            reqwest::Client::builder().dns_resolver(resolver.clone()).build().unwrap();
1248
1249        Mock::given(method("GET"))
1250            .and(path("/.well-known/matrix/client"))
1251            .and(header("host", server_name.as_str()))
1252            .respond_with(
1253                ResponseTemplate::new(200)
1254                    .set_body_json(make_well_known_json(&format!("http://{homeserver_name}"))),
1255            )
1256            .mount(&mock_server)
1257            .await;
1258
1259        Mock::given(method("GET"))
1260            .and(path("/_matrix/client/versions"))
1261            .and(header("host", homeserver_name.as_str()))
1262            .respond_with(ResponseTemplate::new(200).set_body_json(&*test_json::VERSIONS))
1263            .mount(&mock_server)
1264            .await;
1265
1266        // When building a client using server_name_or_homeserver_url with the
1267        // homeserver's URL as the string.
1268        let client = ClientBuilder::new()
1269            .http_client(http_client)
1270            .server_name_or_homeserver_url(format!("http://{homeserver_name}"))
1271            .build()
1272            .await
1273            .unwrap();
1274
1275        // Then homeserver should be the only host that was contacted while
1276        // building.
1277        let resolved_hosts = resolver.hosts.lock().unwrap();
1278        assert!(!resolved_hosts.is_empty(), "The homeserver should have been contacted");
1279        assert!(
1280            resolved_hosts.iter().all(|host| host == "matrix.server.com"),
1281            "A connection was attempted to an unexpected host: {resolved_hosts:?}"
1282        );
1283        assert_eq!(client.homeserver(), Url::parse(&format!("http://{homeserver_name}")).unwrap());
1284        assert_eq!(client.server(), None);
1285    }
1286
1287    #[async_test]
1288    async fn test_sliding_sync_discover_unstable() {
1289        // Given a homeserver with a `/versions` file.
1290        let homeserver = make_mock_homeserver().await;
1291        let mut builder = ClientBuilder::new();
1292
1293        // When building the client with sliding sync to auto-discover the
1294        // unstable version.
1295        builder = builder
1296            .server_name_or_homeserver_url(homeserver.uri())
1297            .sliding_sync_version_builder(SlidingSyncVersionBuilder::DiscoverUnstable);
1298
1299        let client = builder.build().await.unwrap();
1300
1301        // Then, sliding sync has the correct unstable version.
1302        assert_matches!(client.sliding_sync_version(), SlidingSyncVersion::Unstable);
1303    }
1304
1305    #[async_test]
1306    #[cfg(feature = "e2e-encryption")]
1307    async fn test_set_up_decryption_trust_requirement_cross_signed() {
1308        let homeserver = make_mock_homeserver().await;
1309        let builder = ClientBuilder::new()
1310            .server_name_or_homeserver_url(homeserver.uri())
1311            .with_decryption_settings(DecryptionSettings {
1312                sender_device_trust_requirement: TrustRequirement::CrossSigned,
1313            });
1314
1315        let client = builder.build().await.unwrap();
1316        assert_matches!(
1317            client.base_client().decryption_settings.sender_device_trust_requirement,
1318            TrustRequirement::CrossSigned
1319        );
1320    }
1321
1322    #[async_test]
1323    #[cfg(feature = "e2e-encryption")]
1324    async fn test_set_up_decryption_trust_requirement_untrusted() {
1325        let homeserver = make_mock_homeserver().await;
1326
1327        let builder = ClientBuilder::new()
1328            .server_name_or_homeserver_url(homeserver.uri())
1329            .with_decryption_settings(DecryptionSettings {
1330                sender_device_trust_requirement: TrustRequirement::Untrusted,
1331            });
1332
1333        let client = builder.build().await.unwrap();
1334        assert_matches!(
1335            client.base_client().decryption_settings.sender_device_trust_requirement,
1336            TrustRequirement::Untrusted
1337        );
1338    }
1339
1340    #[async_test]
1341    async fn test_cross_process_store_locks_holder_name() {
1342        {
1343            let homeserver = make_mock_homeserver().await;
1344            let client =
1345                ClientBuilder::new().homeserver_url(homeserver.uri()).build().await.unwrap();
1346
1347            assert_let!(
1348                CrossProcessLockConfig::MultiProcess { holder_name } =
1349                    client.cross_process_lock_config()
1350            );
1351            assert_eq!(holder_name, "main");
1352        }
1353
1354        {
1355            let homeserver = make_mock_homeserver().await;
1356            let client = ClientBuilder::new()
1357                .homeserver_url(homeserver.uri())
1358                .cross_process_store_config(CrossProcessLockConfig::multi_process("foo"))
1359                .build()
1360                .await
1361                .unwrap();
1362
1363            assert_let!(
1364                CrossProcessLockConfig::MultiProcess { holder_name } =
1365                    client.cross_process_lock_config()
1366            );
1367            assert_eq!(holder_name, "foo");
1368        }
1369    }
1370
1371    /* Helper functions */
1372
1373    async fn make_mock_homeserver() -> MockServer {
1374        let homeserver = MockServer::start().await;
1375        Mock::given(method("GET"))
1376            .and(path("/_matrix/client/versions"))
1377            .respond_with(ResponseTemplate::new(200).set_body_json(&*test_json::VERSIONS))
1378            .mount(&homeserver)
1379            .await;
1380        Mock::given(method("GET"))
1381            .and(path("/_matrix/client/r0/login"))
1382            .respond_with(ResponseTemplate::new(200).set_body_json(&*test_json::LOGIN_TYPES))
1383            .mount(&homeserver)
1384            .await;
1385        homeserver
1386    }
1387
1388    fn make_well_known_json(homeserver_url: &str) -> JsonValue {
1389        ::serde_json::Value::Object({
1390            let mut object = ::serde_json::Map::new();
1391            let _ = object.insert(
1392                "m.homeserver".into(),
1393                json_internal!({
1394                    "base_url": homeserver_url
1395                }),
1396            );
1397
1398            object
1399        })
1400    }
1401
1402    /// A DNS resolver that records the hostname of every lookup it is asked to
1403    /// make, and resolves all of them to the same address.
1404    #[derive(Debug)]
1405    struct RecordingResolver {
1406        address: SocketAddr,
1407        hosts: StdMutex<Vec<String>>,
1408    }
1409
1410    impl Resolve for RecordingResolver {
1411        fn resolve(&self, name: Name) -> Resolving {
1412            self.hosts.lock().unwrap().push(name.as_str().to_owned());
1413
1414            let addrs: Addrs = Box::new(iter::once(self.address));
1415            Box::pin(future::ready(Ok(addrs)))
1416        }
1417    }
1418}