1mod 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, ThreadingSupport, store::StoreConfig, ttl::TtlValue,
41};
42use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig;
43#[cfg(feature = "sqlite")]
44use matrix_sdk_sqlite::SqliteStoreConfig;
45#[cfg(not(target_family = "wasm"))]
46use reqwest::Certificate;
47use ruma::{
48 OwnedServerName, ServerName,
49 api::{MatrixVersion, SupportedVersions, error::FromHttpResponseError},
50 presence::PresenceState,
51};
52use thiserror::Error;
53#[cfg(feature = "experimental-search")]
54use tokio::sync::Mutex;
55use tokio::sync::OnceCell;
56use tracing::{Span, debug, field::debug, instrument};
57
58use super::{Client, ClientInner};
59#[cfg(feature = "e2e-encryption")]
60use crate::encryption::EncryptionSettings;
61#[cfg(not(target_family = "wasm"))]
62use crate::http_client::HttpSettings;
63#[cfg(feature = "experimental-search")]
64use crate::search_index::SearchIndex;
65#[cfg(feature = "experimental-search")]
66use crate::search_index::SearchIndexStoreKind;
67use crate::{
68 HttpError, IdParseError,
69 authentication::AuthCtx,
70 client::caches::CachedValue::{Cached, NotSet},
71 config::RequestConfig,
72 error::RumaApiError,
73 http_client::HttpClient,
74 media::{DefaultMediaFetcher, MediaFetcher},
75 send_queue::SendQueueData,
76 sliding_sync::VersionBuilder as SlidingSyncVersionBuilder,
77};
78
79#[must_use]
118#[derive(Clone, Debug)]
119pub struct ClientBuilder {
120 homeserver_cfg: Option<HomeserverConfig>,
121 sliding_sync_version_builder: SlidingSyncVersionBuilder,
122 http_cfg: Option<HttpConfig>,
123 store_config: BuilderStoreConfig,
124 request_config: RequestConfig,
125 respect_login_well_known: bool,
126 well_known_lookup_disabled: bool,
127 server_versions: Option<BTreeSet<MatrixVersion>>,
128 handle_refresh_tokens: bool,
129 base_client: Option<BaseClient>,
130 #[cfg(feature = "e2e-encryption")]
131 encryption_settings: EncryptionSettings,
132 #[cfg(feature = "e2e-encryption")]
133 room_key_recipient_strategy: CollectStrategy,
134 #[cfg(feature = "e2e-encryption")]
135 decryption_settings: DecryptionSettings,
136 #[cfg(feature = "e2e-encryption")]
137 enable_share_history_on_invite: bool,
138 enable_automatic_back_pagination: bool,
139 enable_event_cache: bool,
140 cross_process_lock_config: CrossProcessLockConfig,
141 threading_support: ThreadingSupport,
142 #[cfg(feature = "experimental-search")]
143 search_index_store_kind: SearchIndexStoreKind,
144 #[cfg(feature = "experimental-x509-identity-verification")]
145 x509_signer: Option<Arc<dyn RawX509Signer>>,
146 #[cfg(feature = "experimental-x509-identity-verification")]
147 x509_verifier: Option<Arc<dyn RawX509Verifier>>,
148 dm_room_definition: DmRoomDefinition,
149 media_fetcher: Arc<dyn MediaFetcher>,
150}
151
152impl ClientBuilder {
153 const DEFAULT_CROSS_PROCESS_STORE_LOCKS_HOLDER_NAME: &str = "main";
154
155 pub(crate) fn new() -> Self {
156 Self {
157 homeserver_cfg: None,
158 sliding_sync_version_builder: SlidingSyncVersionBuilder::Native,
159 http_cfg: None,
160 store_config: BuilderStoreConfig::Custom(StoreConfig::new(
161 CrossProcessLockConfig::multi_process(
162 Self::DEFAULT_CROSS_PROCESS_STORE_LOCKS_HOLDER_NAME,
163 ),
164 )),
165 request_config: Default::default(),
166 respect_login_well_known: true,
167 well_known_lookup_disabled: false,
168 server_versions: None,
169 handle_refresh_tokens: false,
170 base_client: None,
171 #[cfg(feature = "e2e-encryption")]
172 encryption_settings: Default::default(),
173 #[cfg(feature = "e2e-encryption")]
174 room_key_recipient_strategy: Default::default(),
175 #[cfg(feature = "e2e-encryption")]
176 decryption_settings: DecryptionSettings {
177 sender_device_trust_requirement: TrustRequirement::Untrusted,
178 },
179 #[cfg(feature = "e2e-encryption")]
180 enable_share_history_on_invite: true,
181 enable_automatic_back_pagination: false,
182 enable_event_cache: true,
183 cross_process_lock_config: CrossProcessLockConfig::MultiProcess {
184 holder_name: Self::DEFAULT_CROSS_PROCESS_STORE_LOCKS_HOLDER_NAME.to_owned(),
185 },
186 threading_support: ThreadingSupport::Disabled,
187 #[cfg(feature = "experimental-search")]
188 search_index_store_kind: SearchIndexStoreKind::InMemory,
189 #[cfg(feature = "experimental-x509-identity-verification")]
190 x509_signer: None,
191 #[cfg(feature = "experimental-x509-identity-verification")]
192 x509_verifier: None,
193 dm_room_definition: DmRoomDefinition::MatrixSpec,
194 media_fetcher: Arc::new(DefaultMediaFetcher),
195 }
196 }
197
198 pub fn media_fetcher(mut self, media_fetcher: Arc<dyn MediaFetcher>) -> Self {
201 self.media_fetcher = media_fetcher.clone();
202 self
203 }
204
205 pub fn dm_room_definition(mut self, dm_room_definition: DmRoomDefinition) -> Self {
209 self.dm_room_definition = dm_room_definition;
210 self
211 }
212
213 pub fn homeserver_url(mut self, url: impl AsRef<str>) -> Self {
224 self.homeserver_cfg = Some(HomeserverConfig::HomeserverUrl(url.as_ref().to_owned()));
225 self
226 }
227
228 pub fn server_name(mut self, server_name: &ServerName) -> Self {
242 self.homeserver_cfg = Some(HomeserverConfig::ServerName {
243 server: server_name.to_owned(),
244 protocol: UrlScheme::Https,
246 });
247 self
248 }
249
250 pub fn insecure_server_name_no_tls(mut self, server_name: &ServerName) -> Self {
263 self.homeserver_cfg = Some(HomeserverConfig::ServerName {
264 server: server_name.to_owned(),
265 protocol: UrlScheme::Http,
266 });
267 self
268 }
269
270 pub fn server_name_or_homeserver_url(mut self, server_name_or_url: impl AsRef<str>) -> Self {
286 self.homeserver_cfg = Some(HomeserverConfig::ServerNameOrHomeserverUrl(
287 server_name_or_url.as_ref().to_owned(),
288 ));
289 self
290 }
291
292 pub fn sliding_sync_version_builder(
294 mut self,
295 version_builder: SlidingSyncVersionBuilder,
296 ) -> Self {
297 self.sliding_sync_version_builder = version_builder;
298 self
299 }
300
301 #[cfg(feature = "sqlite")]
303 pub fn sqlite_store(mut self, path: impl AsRef<Path>, passphrase: Option<&str>) -> Self {
304 let sqlite_store_config = SqliteStoreConfig::new(path).passphrase(passphrase);
305 self.store_config =
306 BuilderStoreConfig::Sqlite { config: sqlite_store_config, cache_path: None };
307
308 self
309 }
310
311 #[cfg(feature = "sqlite")]
314 pub fn sqlite_store_with_cache_path(
315 mut self,
316 path: impl AsRef<Path>,
317 cache_path: impl AsRef<Path>,
318 passphrase: Option<&str>,
319 ) -> Self {
320 let sqlite_store_config = SqliteStoreConfig::new(path).passphrase(passphrase);
321 self.store_config = BuilderStoreConfig::Sqlite {
322 config: sqlite_store_config,
323 cache_path: Some(cache_path.as_ref().to_owned()),
324 };
325
326 self
327 }
328
329 #[cfg(feature = "sqlite")]
332 pub fn sqlite_store_with_config_and_cache_path(
333 mut self,
334 config: SqliteStoreConfig,
335 cache_path: Option<impl AsRef<Path>>,
336 ) -> Self {
337 self.store_config = BuilderStoreConfig::Sqlite {
338 config,
339 cache_path: cache_path.map(|cache_path| cache_path.as_ref().to_owned()),
340 };
341
342 self
343 }
344
345 #[cfg(feature = "indexeddb")]
347 pub fn indexeddb_store(mut self, name: &str, passphrase: Option<&str>) -> Self {
348 self.store_config = BuilderStoreConfig::IndexedDb {
349 name: name.to_owned(),
350 passphrase: passphrase.map(ToOwned::to_owned),
351 };
352 self
353 }
354
355 pub fn store_config(mut self, store_config: StoreConfig) -> Self {
379 self.store_config = BuilderStoreConfig::Custom(store_config);
380 self
381 }
382
383 pub fn respect_login_well_known(mut self, value: bool) -> Self {
386 self.respect_login_well_known = value;
387 self
388 }
389
390 pub fn disable_well_known_lookup(mut self, disable: bool) -> Self {
419 self.well_known_lookup_disabled = disable;
420 self
421 }
422
423 pub fn request_config(mut self, request_config: RequestConfig) -> Self {
425 self.request_config = request_config;
426 self
427 }
428
429 #[cfg(not(target_family = "wasm"))]
445 pub fn proxy(mut self, proxy: impl AsRef<str>) -> Self {
446 self.http_settings().proxy = Some(proxy.as_ref().to_owned());
447 self
448 }
449
450 #[cfg(not(target_family = "wasm"))]
452 pub fn disable_ssl_verification(mut self) -> Self {
453 self.http_settings().disable_ssl_verification = true;
454 self
455 }
456
457 #[cfg(not(target_family = "wasm"))]
459 pub fn user_agent(mut self, user_agent: impl AsRef<str>) -> Self {
460 self.http_settings().user_agent = Some(user_agent.as_ref().to_owned());
461 self
462 }
463
464 #[cfg(not(target_family = "wasm"))]
473 pub fn add_root_certificates(mut self, certificates: Vec<Certificate>) -> Self {
474 self.http_settings().additional_root_certificates = certificates;
475 self
476 }
477
478 #[cfg(not(target_family = "wasm"))]
482 pub fn disable_built_in_root_certificates(mut self) -> Self {
483 self.http_settings().disable_built_in_root_certificates = true;
484 self
485 }
486
487 pub fn http_client(mut self, client: reqwest::Client) -> Self {
497 self.http_cfg = Some(HttpConfig::Custom(client));
498 self
499 }
500
501 pub fn server_versions(mut self, value: impl IntoIterator<Item = MatrixVersion>) -> Self {
506 self.server_versions = Some(value.into_iter().collect());
507 self
508 }
509
510 #[cfg(not(target_family = "wasm"))]
511 fn http_settings(&mut self) -> &mut HttpSettings {
512 self.http_cfg.get_or_insert_with(Default::default).settings()
513 }
514
515 pub fn handle_refresh_tokens(mut self) -> Self {
537 self.handle_refresh_tokens = true;
538 self
539 }
540
541 #[doc(hidden)]
543 pub fn base_client(mut self, base_client: BaseClient) -> Self {
544 self.base_client = Some(base_client);
545 self
546 }
547
548 #[cfg(feature = "e2e-encryption")]
551 pub fn with_encryption_settings(mut self, settings: EncryptionSettings) -> Self {
552 self.encryption_settings = settings;
553 self
554 }
555
556 #[cfg(feature = "e2e-encryption")]
559 pub fn with_room_key_recipient_strategy(mut self, strategy: CollectStrategy) -> Self {
560 self.room_key_recipient_strategy = strategy;
561 self
562 }
563
564 #[cfg(feature = "e2e-encryption")]
566 pub fn with_decryption_settings(mut self, decryption_settings: DecryptionSettings) -> Self {
567 self.decryption_settings = decryption_settings;
568 self
569 }
570
571 #[cfg(feature = "e2e-encryption")]
579 pub fn with_enable_share_history_on_invite(
580 mut self,
581 enable_share_history_on_invite: bool,
582 ) -> Self {
583 self.enable_share_history_on_invite = enable_share_history_on_invite;
584 self
585 }
586
587 pub fn with_enable_automatic_back_pagination(mut self, enable: bool) -> Self {
593 self.enable_automatic_back_pagination = enable;
594 self
595 }
596
597 pub fn with_event_cache(mut self, enable: bool) -> Self {
610 self.enable_event_cache = enable;
611 self
612 }
613
614 pub fn cross_process_store_config(
624 mut self,
625 cross_process_store_config: CrossProcessLockConfig,
626 ) -> Self {
627 self.cross_process_lock_config = cross_process_store_config;
628 self
629 }
630
631 pub fn with_threading_support(mut self, threading_support: ThreadingSupport) -> Self {
635 self.threading_support = threading_support;
636 self
637 }
638
639 #[cfg(feature = "experimental-search")]
641 pub fn search_index_store(mut self, kind: SearchIndexStoreKind) -> Self {
642 self.search_index_store_kind = kind;
643 self
644 }
645
646 #[cfg(feature = "experimental-x509-identity-verification")]
649 pub fn with_x509_signer(mut self, x509_signer: Option<Arc<dyn RawX509Signer>>) -> Self {
650 self.x509_signer = x509_signer;
651 self
652 }
653
654 #[cfg(feature = "experimental-x509-identity-verification")]
657 pub fn with_x509_verifier(mut self, x509_verifier: Option<Arc<dyn RawX509Verifier>>) -> Self {
658 self.x509_verifier = x509_verifier;
659 self
660 }
661
662 #[instrument(skip_all, target = "matrix_sdk::client", fields(homeserver))]
675 pub async fn build(self) -> Result<Client, ClientBuildError> {
676 debug!("Starting to build the Client");
677
678 let homeserver_cfg = self.homeserver_cfg.ok_or(ClientBuildError::MissingHomeserver)?;
679 Span::current().record("homeserver", debug(&homeserver_cfg));
680
681 let base_client = if let Some(base_client) = self.base_client {
682 base_client
683 } else {
684 #[allow(unused_mut)]
685 let mut client = BaseClient::new(
686 build_store_config(self.store_config, &self.cross_process_lock_config).await?,
687 self.threading_support,
688 self.dm_room_definition,
689 );
690
691 #[cfg(feature = "e2e-encryption")]
692 {
693 client.room_key_recipient_strategy = self.room_key_recipient_strategy;
694 client.decryption_settings = self.decryption_settings;
695 }
696
697 #[cfg(feature = "experimental-x509-identity-verification")]
698 client.set_x509_signer(self.x509_signer);
699 #[cfg(feature = "experimental-x509-identity-verification")]
700 client.set_x509_verifier(self.x509_verifier);
701
702 client
703 };
704
705 let http_client = HttpClient::new(
706 #[cfg_attr(target_family = "wasm", allow(clippy::infallible_destructuring_match))]
707 match self.http_cfg.unwrap_or_default() {
708 #[cfg(not(target_family = "wasm"))]
709 HttpConfig::Settings(mut settings) => {
710 settings.timeout = self.request_config.timeout;
711 settings.make_client()?
712 }
713 HttpConfig::Custom(c) => c,
714 },
715 self.request_config,
716 );
717
718 #[allow(unused_variables)]
719 let HomeserverDiscoveryResult { server, homeserver, supported_versions, well_known } =
720 homeserver_cfg.discover(&http_client, self.well_known_lookup_disabled).await?;
721
722 let sliding_sync_version = {
723 let supported_versions = match supported_versions {
724 Some(versions) => Some(versions),
725 None if self.sliding_sync_version_builder.needs_get_supported_versions() => {
726 Some(get_supported_versions(&homeserver, &http_client).await?)
727 }
728 None => None,
729 };
730
731 let version = self.sliding_sync_version_builder.build(
732 supported_versions.map(|response| response.as_supported_versions()).as_ref(),
733 )?;
734
735 tracing::info!(?version, "selected sliding sync version");
736
737 version
738 };
739
740 let allow_insecure_oauth = homeserver.scheme() == "http";
741 let auth_ctx = Arc::new(AuthCtx::new(self.handle_refresh_tokens, allow_insecure_oauth));
742
743 let send_queue = Arc::new(SendQueueData::new(true));
745
746 let supported_versions = match self.server_versions {
747 Some(versions) => Cached(TtlValue::without_expiry(SupportedVersions {
748 versions,
749 features: Default::default(),
750 })),
751 None => NotSet,
752 };
753 let well_known = match well_known {
754 Some(well_known) => Cached(TtlValue::new(Some(well_known.into()))),
755 None => NotSet,
756 };
757
758 let thread_subscriptions_catchup = OnceCell::new();
759
760 #[cfg(feature = "experimental-search")]
761 let search_index =
762 SearchIndex::new(Arc::new(Mutex::new(HashMap::new())), self.search_index_store_kind);
763
764 let inner = ClientInner::new(
765 auth_ctx,
766 server,
767 homeserver,
768 sliding_sync_version,
769 Arc::new(StdRwLock::new(PresenceState::Online)),
770 http_client,
771 base_client,
772 supported_versions,
773 well_known,
774 self.respect_login_well_known,
775 self.well_known_lookup_disabled,
776 self.enable_automatic_back_pagination,
777 self.enable_event_cache,
778 send_queue,
779 #[cfg(feature = "e2e-encryption")]
780 self.encryption_settings,
781 #[cfg(feature = "e2e-encryption")]
782 self.enable_share_history_on_invite,
783 self.cross_process_lock_config,
784 #[cfg(feature = "experimental-search")]
785 search_index,
786 thread_subscriptions_catchup,
787 self.media_fetcher.clone(),
788 )
789 .await;
790
791 debug!("Done building the Client");
792
793 Ok(Client { inner })
794 }
795}
796
797pub fn sanitize_server_name(s: &str) -> crate::Result<OwnedServerName, IdParseError> {
801 ServerName::parse(
802 s.trim().trim_start_matches("http://").trim_start_matches("https://").trim_end_matches('/'),
803 )
804}
805
806#[allow(clippy::unused_async, unused)] async fn build_store_config(
808 builder_config: BuilderStoreConfig,
809 cross_process_store_config: &CrossProcessLockConfig,
810) -> Result<StoreConfig, ClientBuildError> {
811 #[allow(clippy::infallible_destructuring_match)]
812 let store_config = match builder_config {
813 #[cfg(feature = "sqlite")]
814 BuilderStoreConfig::Sqlite { config, cache_path } => {
815 let config_with_cache_path = if let Some(ref cache_path) = cache_path {
816 config.clone().path(cache_path)
817 } else {
818 config.clone()
819 };
820
821 #[cfg(feature = "e2e-encryption")]
822 let (state_store, event_cache_store, media_store, crypto_store) = try_join!(
823 matrix_sdk_sqlite::SqliteStateStore::open_with_config(&config),
824 matrix_sdk_sqlite::SqliteEventCacheStore::open_with_config(&config_with_cache_path),
825 matrix_sdk_sqlite::SqliteMediaStore::open_with_config(&config_with_cache_path),
826 matrix_sdk_sqlite::SqliteCryptoStore::open_with_config(&config),
827 )?;
828 #[cfg(not(feature = "e2e-encryption"))]
829 let (state_store, event_cache_store, media_store) = try_join!(
830 matrix_sdk_sqlite::SqliteStateStore::open_with_config(&config),
831 matrix_sdk_sqlite::SqliteEventCacheStore::open_with_config(&config_with_cache_path),
832 matrix_sdk_sqlite::SqliteMediaStore::open_with_config(&config),
833 )?;
834 let store_config = StoreConfig::new(cross_process_store_config.clone())
835 .state_store(state_store)
836 .event_cache_store(event_cache_store)
837 .media_store(media_store);
838
839 #[cfg(feature = "e2e-encryption")]
840 let store_config = store_config.crypto_store(crypto_store);
841
842 store_config
843 }
844
845 #[cfg(feature = "indexeddb")]
846 BuilderStoreConfig::IndexedDb { name, passphrase } => {
847 build_indexeddb_store_config(
848 &name,
849 passphrase.as_deref(),
850 cross_process_store_config.clone(),
851 )
852 .await?
853 }
854
855 BuilderStoreConfig::Custom(config) => config,
856 };
857 Ok(store_config)
858}
859
860#[cfg(all(target_family = "wasm", feature = "indexeddb"))]
863async fn build_indexeddb_store_config(
864 name: &str,
865 passphrase: Option<&str>,
866 cross_process_store_config: CrossProcessLockConfig,
867) -> Result<StoreConfig, ClientBuildError> {
868 let stores = matrix_sdk_indexeddb::IndexeddbStores::open(name, passphrase).await?;
869 let store_config = StoreConfig::new(cross_process_store_config)
870 .state_store(stores.state)
871 .event_cache_store(stores.event_cache)
872 .media_store(stores.media);
873
874 #[cfg(feature = "e2e-encryption")]
875 let store_config = store_config.crypto_store(stores.crypto);
876
877 Ok(store_config)
878}
879
880#[cfg(all(not(target_family = "wasm"), feature = "indexeddb"))]
881#[allow(clippy::unused_async)]
882async fn build_indexeddb_store_config(
883 _name: &str,
884 _passphrase: Option<&str>,
885 _cross_process_store_config: CrossProcessLockConfig,
886) -> Result<StoreConfig, ClientBuildError> {
887 panic!("the IndexedDB is only available on the 'wasm32' arch")
888}
889
890#[derive(Clone, Debug)]
891enum HttpConfig {
892 #[cfg(not(target_family = "wasm"))]
893 Settings(HttpSettings),
894 Custom(reqwest::Client),
895}
896
897#[cfg(not(target_family = "wasm"))]
898impl HttpConfig {
899 fn settings(&mut self) -> &mut HttpSettings {
900 match self {
901 Self::Settings(s) => s,
902 Self::Custom(_) => {
903 *self = Self::default();
904 match self {
905 Self::Settings(s) => s,
906 Self::Custom(_) => unreachable!(),
907 }
908 }
909 }
910 }
911}
912
913impl Default for HttpConfig {
914 fn default() -> Self {
915 #[cfg(not(target_family = "wasm"))]
916 return Self::Settings(HttpSettings::default());
917
918 #[cfg(target_family = "wasm")]
919 return Self::Custom(reqwest::Client::new());
920 }
921}
922
923#[derive(Clone)]
924enum BuilderStoreConfig {
925 #[cfg(feature = "sqlite")]
926 Sqlite {
927 config: SqliteStoreConfig,
928 cache_path: Option<PathBuf>,
929 },
930 #[cfg(feature = "indexeddb")]
931 IndexedDb {
932 name: String,
933 passphrase: Option<String>,
934 },
935 Custom(StoreConfig),
936}
937
938#[cfg(not(tarpaulin_include))]
939impl fmt::Debug for BuilderStoreConfig {
940 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
941 #[allow(clippy::infallible_destructuring_match)]
942 match self {
943 #[cfg(feature = "sqlite")]
944 Self::Sqlite { config, cache_path, .. } => f
945 .debug_struct("Sqlite")
946 .field("config", config)
947 .field("cache_path", cache_path)
948 .finish_non_exhaustive(),
949
950 #[cfg(feature = "indexeddb")]
951 Self::IndexedDb { name, .. } => {
952 f.debug_struct("IndexedDb").field("name", name).finish_non_exhaustive()
953 }
954
955 Self::Custom(store_config) => f.debug_tuple("Custom").field(store_config).finish(),
956 }
957 }
958}
959
960#[derive(Debug, Error)]
962pub enum ClientBuildError {
963 #[error("No homeserver or user ID was configured")]
965 MissingHomeserver,
966
967 #[error("The supplied server name is invalid")]
969 InvalidServerName,
970
971 #[error(
975 "Homeserver discovery requires a .well-known lookup, which was disabled; \
976 use `ClientBuilder::homeserver_url` instead"
977 )]
978 WellKnownLookupDisabled,
979
980 #[error("Error looking up the .well-known endpoint on auto-discovery")]
982 AutoDiscovery(Box<FromHttpResponseError<RumaApiError>>),
983
984 #[error(transparent)]
986 SlidingSyncVersion(#[from] crate::sliding_sync::VersionBuilderError),
987
988 #[error(transparent)]
990 Url(#[from] url::ParseError),
991
992 #[error(transparent)]
994 Http(#[from] HttpError),
995
996 #[cfg(feature = "indexeddb")]
998 #[error(transparent)]
999 IndexeddbStore(#[from] matrix_sdk_indexeddb::OpenStoreError),
1000
1001 #[cfg(feature = "sqlite")]
1003 #[error(transparent)]
1004 SqliteStore(#[from] matrix_sdk_sqlite::OpenStoreError),
1005}
1006
1007#[cfg(all(test, not(target_family = "wasm")))]
1009pub(crate) mod tests {
1010 use std::{future, iter, net::SocketAddr, sync::Mutex as StdMutex};
1011
1012 use assert_matches::assert_matches;
1013 use matrix_sdk_test::{async_test, test_json};
1014 use reqwest::dns::{Addrs, Name, Resolve, Resolving};
1015 use serde_json::{Value as JsonValue, json_internal};
1016 use strass::assert_let;
1017 use url::Url;
1018 use wiremock::{
1019 Mock, MockServer, ResponseTemplate,
1020 matchers::{header, method, path},
1021 };
1022
1023 use super::*;
1024 use crate::sliding_sync::Version as SlidingSyncVersion;
1025
1026 #[test]
1027 fn test_sanitize_server_name() {
1028 assert_eq!(sanitize_server_name("matrix.org").unwrap().as_str(), "matrix.org");
1029 assert_eq!(sanitize_server_name("https://matrix.org").unwrap().as_str(), "matrix.org");
1030 assert_eq!(sanitize_server_name("http://matrix.org").unwrap().as_str(), "matrix.org");
1031 assert_eq!(
1032 sanitize_server_name("https://matrix.server.org").unwrap().as_str(),
1033 "matrix.server.org"
1034 );
1035 assert_eq!(
1036 sanitize_server_name("https://matrix.server.org/").unwrap().as_str(),
1037 "matrix.server.org"
1038 );
1039 assert_eq!(
1040 sanitize_server_name(" https://matrix.server.org// ").unwrap().as_str(),
1041 "matrix.server.org"
1042 );
1043 assert_matches!(sanitize_server_name("https://matrix.server.org/something"), Err(_))
1044 }
1045
1046 #[async_test]
1054 async fn test_discovery_invalid_server() {
1055 let mut builder = ClientBuilder::new();
1057
1058 builder = builder.server_name_or_homeserver_url("⚠️ This won't work 🚫");
1060 let error = builder.build().await.unwrap_err();
1061
1062 assert_matches!(error, ClientBuildError::InvalidServerName);
1064 }
1065
1066 #[async_test]
1067 async fn test_discovery_no_server() {
1068 let mut builder = ClientBuilder::new();
1070
1071 builder = builder.server_name_or_homeserver_url("localhost:3456");
1073 let error = builder.build().await.unwrap_err();
1074
1075 println!("{error}");
1077 assert_matches!(error, ClientBuildError::Http(_));
1078 }
1079
1080 #[async_test]
1081 async fn test_discovery_web_server() {
1082 let server = MockServer::start().await;
1085 let mut builder = ClientBuilder::new();
1086
1087 builder = builder.server_name_or_homeserver_url(server.uri());
1089 let error = builder.build().await.unwrap_err();
1090
1091 assert_let!(ClientBuildError::AutoDiscovery(e) = error);
1093 assert_matches!(*e, FromHttpResponseError::Server(_));
1094 }
1095
1096 #[async_test]
1097 async fn test_discovery_direct_legacy() {
1098 let homeserver = make_mock_homeserver().await;
1100 let mut builder = ClientBuilder::new();
1101
1102 builder = builder.server_name_or_homeserver_url(homeserver.uri());
1104 let _client = builder.build().await.unwrap();
1105
1106 assert!(_client.sliding_sync_version().is_native());
1108 }
1109
1110 #[async_test]
1111 async fn test_discovery_well_known_parse_error() {
1112 let server = MockServer::start().await;
1114 let homeserver = make_mock_homeserver().await;
1115 let mut builder = ClientBuilder::new();
1116
1117 let well_known = make_well_known_json(&homeserver.uri());
1118 let bad_json = well_known.to_string().replace(',', "");
1119 Mock::given(method("GET"))
1120 .and(path("/.well-known/matrix/client"))
1121 .respond_with(ResponseTemplate::new(200).set_body_json(bad_json))
1122 .mount(&server)
1123 .await;
1124
1125 builder = builder.server_name_or_homeserver_url(server.uri());
1127 let error = builder.build().await.unwrap_err();
1128
1129 assert_let!(ClientBuildError::AutoDiscovery(e) = error);
1131 assert_matches!(*e, FromHttpResponseError::Deserialization(_));
1132 }
1133
1134 #[async_test]
1135 async fn test_discovery_well_known_legacy() {
1136 let server = MockServer::start().await;
1139 let homeserver = make_mock_homeserver().await;
1140 let mut builder = ClientBuilder::new();
1141
1142 Mock::given(method("GET"))
1143 .and(path("/.well-known/matrix/client"))
1144 .respond_with(
1145 ResponseTemplate::new(200).set_body_json(make_well_known_json(&homeserver.uri())),
1146 )
1147 .mount(&server)
1148 .await;
1149
1150 builder = builder.server_name_or_homeserver_url(server.uri());
1152 let client = builder.build().await.unwrap();
1153
1154 assert!(client.sliding_sync_version().is_native());
1158 }
1159
1160 #[async_test]
1161 async fn test_discovery_server_name_with_well_known_lookup_disabled() {
1162 let builder = ClientBuilder::new()
1164 .server_name(&ServerName::parse("example.org").unwrap())
1165 .disable_well_known_lookup(true);
1166
1167 let error = builder.build().await.unwrap_err();
1170
1171 assert_matches!(error, ClientBuildError::WellKnownLookupDisabled);
1174
1175 let error = ClientBuilder::new()
1177 .insecure_server_name_no_tls(&ServerName::parse("example.org").unwrap())
1178 .disable_well_known_lookup(true)
1179 .build()
1180 .await
1181 .unwrap_err();
1182
1183 assert_matches!(error, ClientBuildError::WellKnownLookupDisabled);
1184 }
1185
1186 #[async_test]
1187 async fn test_discovery_server_name_or_url_with_well_known_lookup_disabled() {
1188 let homeserver = make_mock_homeserver().await;
1192 Mock::given(method("GET"))
1193 .and(path("/.well-known/matrix/client"))
1194 .respond_with(
1195 ResponseTemplate::new(200).set_body_json(make_well_known_json(&homeserver.uri())),
1196 )
1197 .named("well-known mock")
1198 .expect(0)
1199 .mount(&homeserver)
1200 .await;
1201
1202 let client = ClientBuilder::new()
1204 .server_name_or_homeserver_url(homeserver.uri())
1205 .disable_well_known_lookup(true)
1206 .build()
1207 .await
1208 .unwrap();
1209
1210 assert_eq!(client.homeserver().as_str().trim_end_matches('/'), homeserver.uri());
1213 }
1214
1215 #[async_test]
1216 async fn test_homeserver_url_never_contacts_the_server_name() {
1217 let mock_server = MockServer::start().await;
1221 let address = *mock_server.address();
1222 let port = address.port();
1223 let server_name = format!("servername.com:{port}");
1224 let homeserver_name = format!("matrix.server.com:{port}");
1225
1226 let resolver = Arc::new(RecordingResolver { address, hosts: StdMutex::new(Vec::new()) });
1228 let http_client =
1229 reqwest::Client::builder().dns_resolver(resolver.clone()).build().unwrap();
1230
1231 Mock::given(method("GET"))
1232 .and(path("/.well-known/matrix/client"))
1233 .and(header("host", server_name.as_str()))
1234 .respond_with(
1235 ResponseTemplate::new(200)
1236 .set_body_json(make_well_known_json(&format!("http://{homeserver_name}"))),
1237 )
1238 .mount(&mock_server)
1239 .await;
1240
1241 Mock::given(method("GET"))
1242 .and(path("/_matrix/client/versions"))
1243 .and(header("host", homeserver_name.as_str()))
1244 .respond_with(ResponseTemplate::new(200).set_body_json(&*test_json::VERSIONS))
1245 .mount(&mock_server)
1246 .await;
1247
1248 let client = ClientBuilder::new()
1251 .http_client(http_client)
1252 .server_name_or_homeserver_url(format!("http://{homeserver_name}"))
1253 .build()
1254 .await
1255 .unwrap();
1256
1257 let resolved_hosts = resolver.hosts.lock().unwrap();
1260 assert!(!resolved_hosts.is_empty(), "The homeserver should have been contacted");
1261 assert!(
1262 resolved_hosts.iter().all(|host| host == "matrix.server.com"),
1263 "A connection was attempted to an unexpected host: {resolved_hosts:?}"
1264 );
1265 assert_eq!(client.homeserver(), Url::parse(&format!("http://{homeserver_name}")).unwrap());
1266 assert_eq!(client.server(), None);
1267 }
1268
1269 #[async_test]
1270 async fn test_sliding_sync_discover_native() {
1271 let homeserver = make_mock_homeserver().await;
1273 let mut builder = ClientBuilder::new();
1274
1275 builder = builder
1278 .server_name_or_homeserver_url(homeserver.uri())
1279 .sliding_sync_version_builder(SlidingSyncVersionBuilder::DiscoverNative);
1280
1281 let client = builder.build().await.unwrap();
1282
1283 assert_matches!(client.sliding_sync_version(), SlidingSyncVersion::Native);
1285 }
1286
1287 #[async_test]
1288 #[cfg(feature = "e2e-encryption")]
1289 async fn test_set_up_decryption_trust_requirement_cross_signed() {
1290 let homeserver = make_mock_homeserver().await;
1291 let builder = ClientBuilder::new()
1292 .server_name_or_homeserver_url(homeserver.uri())
1293 .with_decryption_settings(DecryptionSettings {
1294 sender_device_trust_requirement: TrustRequirement::CrossSigned,
1295 });
1296
1297 let client = builder.build().await.unwrap();
1298 assert_matches!(
1299 client.base_client().decryption_settings.sender_device_trust_requirement,
1300 TrustRequirement::CrossSigned
1301 );
1302 }
1303
1304 #[async_test]
1305 #[cfg(feature = "e2e-encryption")]
1306 async fn test_set_up_decryption_trust_requirement_untrusted() {
1307 let homeserver = make_mock_homeserver().await;
1308
1309 let builder = ClientBuilder::new()
1310 .server_name_or_homeserver_url(homeserver.uri())
1311 .with_decryption_settings(DecryptionSettings {
1312 sender_device_trust_requirement: TrustRequirement::Untrusted,
1313 });
1314
1315 let client = builder.build().await.unwrap();
1316 assert_matches!(
1317 client.base_client().decryption_settings.sender_device_trust_requirement,
1318 TrustRequirement::Untrusted
1319 );
1320 }
1321
1322 #[async_test]
1323 async fn test_cross_process_store_locks_holder_name() {
1324 {
1325 let homeserver = make_mock_homeserver().await;
1326 let client =
1327 ClientBuilder::new().homeserver_url(homeserver.uri()).build().await.unwrap();
1328
1329 assert_let!(
1330 CrossProcessLockConfig::MultiProcess { holder_name } =
1331 client.cross_process_lock_config()
1332 );
1333 assert_eq!(holder_name, "main");
1334 }
1335
1336 {
1337 let homeserver = make_mock_homeserver().await;
1338 let client = ClientBuilder::new()
1339 .homeserver_url(homeserver.uri())
1340 .cross_process_store_config(CrossProcessLockConfig::multi_process("foo"))
1341 .build()
1342 .await
1343 .unwrap();
1344
1345 assert_let!(
1346 CrossProcessLockConfig::MultiProcess { holder_name } =
1347 client.cross_process_lock_config()
1348 );
1349 assert_eq!(holder_name, "foo");
1350 }
1351 }
1352
1353 async fn make_mock_homeserver() -> MockServer {
1356 let homeserver = MockServer::start().await;
1357 Mock::given(method("GET"))
1358 .and(path("/_matrix/client/versions"))
1359 .respond_with(ResponseTemplate::new(200).set_body_json(&*test_json::VERSIONS))
1360 .mount(&homeserver)
1361 .await;
1362 Mock::given(method("GET"))
1363 .and(path("/_matrix/client/r0/login"))
1364 .respond_with(ResponseTemplate::new(200).set_body_json(&*test_json::LOGIN_TYPES))
1365 .mount(&homeserver)
1366 .await;
1367 homeserver
1368 }
1369
1370 fn make_well_known_json(homeserver_url: &str) -> JsonValue {
1371 ::serde_json::Value::Object({
1372 let mut object = ::serde_json::Map::new();
1373 let _ = object.insert(
1374 "m.homeserver".into(),
1375 json_internal!({
1376 "base_url": homeserver_url
1377 }),
1378 );
1379
1380 object
1381 })
1382 }
1383
1384 #[derive(Debug)]
1387 struct RecordingResolver {
1388 address: SocketAddr,
1389 hosts: StdMutex<Vec<String>>,
1390 }
1391
1392 impl Resolve for RecordingResolver {
1393 fn resolve(&self, name: Name) -> Resolving {
1394 self.hosts.lock().unwrap().push(name.as_str().to_owned());
1395
1396 let addrs: Addrs = Box::new(iter::once(self.address));
1397 Box::pin(future::ready(Ok(addrs)))
1398 }
1399 }
1400}