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::{collections::BTreeSet, fmt, sync::Arc};
25
26#[cfg(feature = "sqlite")]
27use futures_util::try_join;
28use homeserver_config::*;
29#[cfg(feature = "e2e-encryption")]
30use matrix_sdk_base::crypto::DecryptionSettings;
31#[cfg(feature = "e2e-encryption")]
32use matrix_sdk_base::crypto::{CollectStrategy, TrustRequirement};
33use matrix_sdk_base::{
34 BaseClient, DmRoomDefinition, ThreadingSupport, store::StoreConfig, ttl::TtlValue,
35};
36use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig;
37#[cfg(feature = "sqlite")]
38use matrix_sdk_sqlite::SqliteStoreConfig;
39#[cfg(not(target_family = "wasm"))]
40use reqwest::Certificate;
41use ruma::{
42 OwnedServerName, ServerName,
43 api::{MatrixVersion, SupportedVersions, error::FromHttpResponseError},
44};
45use thiserror::Error;
46#[cfg(feature = "experimental-search")]
47use tokio::sync::Mutex;
48use tokio::sync::OnceCell;
49use tracing::{Span, debug, field::debug, instrument};
50
51use super::{Client, ClientInner};
52#[cfg(feature = "e2e-encryption")]
53use crate::encryption::EncryptionSettings;
54#[cfg(not(target_family = "wasm"))]
55use crate::http_client::HttpSettings;
56#[cfg(feature = "experimental-search")]
57use crate::search_index::SearchIndex;
58#[cfg(feature = "experimental-search")]
59use crate::search_index::SearchIndexStoreKind;
60use crate::{
61 HttpError, IdParseError,
62 authentication::AuthCtx,
63 client::caches::CachedValue::{Cached, NotSet},
64 config::RequestConfig,
65 error::RumaApiError,
66 http_client::HttpClient,
67 send_queue::SendQueueData,
68 sliding_sync::VersionBuilder as SlidingSyncVersionBuilder,
69};
70
71#[must_use]
110#[derive(Clone, Debug)]
111pub struct ClientBuilder {
112 homeserver_cfg: Option<HomeserverConfig>,
113 sliding_sync_version_builder: SlidingSyncVersionBuilder,
114 http_cfg: Option<HttpConfig>,
115 store_config: BuilderStoreConfig,
116 request_config: RequestConfig,
117 respect_login_well_known: bool,
118 server_versions: Option<BTreeSet<MatrixVersion>>,
119 handle_refresh_tokens: bool,
120 base_client: Option<BaseClient>,
121 #[cfg(feature = "e2e-encryption")]
122 encryption_settings: EncryptionSettings,
123 #[cfg(feature = "e2e-encryption")]
124 room_key_recipient_strategy: CollectStrategy,
125 #[cfg(feature = "e2e-encryption")]
126 decryption_settings: DecryptionSettings,
127 #[cfg(feature = "e2e-encryption")]
128 enable_share_history_on_invite: bool,
129 cross_process_lock_config: CrossProcessLockConfig,
130 threading_support: ThreadingSupport,
131 #[cfg(feature = "experimental-search")]
132 search_index_store_kind: SearchIndexStoreKind,
133 dm_room_definition: DmRoomDefinition,
134}
135
136impl ClientBuilder {
137 const DEFAULT_CROSS_PROCESS_STORE_LOCKS_HOLDER_NAME: &str = "main";
138
139 pub(crate) fn new() -> Self {
140 Self {
141 homeserver_cfg: None,
142 sliding_sync_version_builder: SlidingSyncVersionBuilder::Native,
143 http_cfg: None,
144 store_config: BuilderStoreConfig::Custom(StoreConfig::new(
145 CrossProcessLockConfig::multi_process(
146 Self::DEFAULT_CROSS_PROCESS_STORE_LOCKS_HOLDER_NAME,
147 ),
148 )),
149 request_config: Default::default(),
150 respect_login_well_known: true,
151 server_versions: None,
152 handle_refresh_tokens: false,
153 base_client: None,
154 #[cfg(feature = "e2e-encryption")]
155 encryption_settings: Default::default(),
156 #[cfg(feature = "e2e-encryption")]
157 room_key_recipient_strategy: Default::default(),
158 #[cfg(feature = "e2e-encryption")]
159 decryption_settings: DecryptionSettings {
160 sender_device_trust_requirement: TrustRequirement::Untrusted,
161 },
162 #[cfg(feature = "e2e-encryption")]
163 enable_share_history_on_invite: true,
164 cross_process_lock_config: CrossProcessLockConfig::MultiProcess {
165 holder_name: Self::DEFAULT_CROSS_PROCESS_STORE_LOCKS_HOLDER_NAME.to_owned(),
166 },
167 threading_support: ThreadingSupport::Disabled,
168 #[cfg(feature = "experimental-search")]
169 search_index_store_kind: SearchIndexStoreKind::InMemory,
170 dm_room_definition: DmRoomDefinition::MatrixSpec,
171 }
172 }
173
174 pub fn dm_room_definition(mut self, dm_room_definition: DmRoomDefinition) -> Self {
178 self.dm_room_definition = dm_room_definition;
179 self
180 }
181
182 pub fn homeserver_url(mut self, url: impl AsRef<str>) -> Self {
189 self.homeserver_cfg = Some(HomeserverConfig::HomeserverUrl(url.as_ref().to_owned()));
190 self
191 }
192
193 pub fn server_name(mut self, server_name: &ServerName) -> Self {
203 self.homeserver_cfg = Some(HomeserverConfig::ServerName {
204 server: server_name.to_owned(),
205 protocol: UrlScheme::Https,
207 });
208 self
209 }
210
211 pub fn insecure_server_name_no_tls(mut self, server_name: &ServerName) -> Self {
220 self.homeserver_cfg = Some(HomeserverConfig::ServerName {
221 server: server_name.to_owned(),
222 protocol: UrlScheme::Http,
223 });
224 self
225 }
226
227 pub fn server_name_or_homeserver_url(mut self, server_name_or_url: impl AsRef<str>) -> Self {
238 self.homeserver_cfg = Some(HomeserverConfig::ServerNameOrHomeserverUrl(
239 server_name_or_url.as_ref().to_owned(),
240 ));
241 self
242 }
243
244 pub fn sliding_sync_version_builder(
246 mut self,
247 version_builder: SlidingSyncVersionBuilder,
248 ) -> Self {
249 self.sliding_sync_version_builder = version_builder;
250 self
251 }
252
253 #[cfg(feature = "sqlite")]
255 pub fn sqlite_store(mut self, path: impl AsRef<Path>, passphrase: Option<&str>) -> Self {
256 let sqlite_store_config = SqliteStoreConfig::new(path).passphrase(passphrase);
257 self.store_config =
258 BuilderStoreConfig::Sqlite { config: sqlite_store_config, cache_path: None };
259
260 self
261 }
262
263 #[cfg(feature = "sqlite")]
266 pub fn sqlite_store_with_cache_path(
267 mut self,
268 path: impl AsRef<Path>,
269 cache_path: impl AsRef<Path>,
270 passphrase: Option<&str>,
271 ) -> Self {
272 let sqlite_store_config = SqliteStoreConfig::new(path).passphrase(passphrase);
273 self.store_config = BuilderStoreConfig::Sqlite {
274 config: sqlite_store_config,
275 cache_path: Some(cache_path.as_ref().to_owned()),
276 };
277
278 self
279 }
280
281 #[cfg(feature = "sqlite")]
284 pub fn sqlite_store_with_config_and_cache_path(
285 mut self,
286 config: SqliteStoreConfig,
287 cache_path: Option<impl AsRef<Path>>,
288 ) -> Self {
289 self.store_config = BuilderStoreConfig::Sqlite {
290 config,
291 cache_path: cache_path.map(|cache_path| cache_path.as_ref().to_owned()),
292 };
293
294 self
295 }
296
297 #[cfg(feature = "indexeddb")]
299 pub fn indexeddb_store(mut self, name: &str, passphrase: Option<&str>) -> Self {
300 self.store_config = BuilderStoreConfig::IndexedDb {
301 name: name.to_owned(),
302 passphrase: passphrase.map(ToOwned::to_owned),
303 };
304 self
305 }
306
307 pub fn store_config(mut self, store_config: StoreConfig) -> Self {
331 self.store_config = BuilderStoreConfig::Custom(store_config);
332 self
333 }
334
335 pub fn respect_login_well_known(mut self, value: bool) -> Self {
338 self.respect_login_well_known = value;
339 self
340 }
341
342 pub fn request_config(mut self, request_config: RequestConfig) -> Self {
344 self.request_config = request_config;
345 self
346 }
347
348 #[cfg(not(target_family = "wasm"))]
364 pub fn proxy(mut self, proxy: impl AsRef<str>) -> Self {
365 self.http_settings().proxy = Some(proxy.as_ref().to_owned());
366 self
367 }
368
369 #[cfg(not(target_family = "wasm"))]
371 pub fn disable_ssl_verification(mut self) -> Self {
372 self.http_settings().disable_ssl_verification = true;
373 self
374 }
375
376 #[cfg(not(target_family = "wasm"))]
378 pub fn user_agent(mut self, user_agent: impl AsRef<str>) -> Self {
379 self.http_settings().user_agent = Some(user_agent.as_ref().to_owned());
380 self
381 }
382
383 #[cfg(not(target_family = "wasm"))]
392 pub fn add_root_certificates(mut self, certificates: Vec<Certificate>) -> Self {
393 self.http_settings().additional_root_certificates = certificates;
394 self
395 }
396
397 #[cfg(target_os = "android")]
402 pub fn add_raw_root_certificates(mut self, raw_certificates: Vec<Vec<u8>>) -> Self {
403 self.http_settings().additional_raw_root_certificates = raw_certificates;
404 self
405 }
406
407 #[cfg(not(target_family = "wasm"))]
411 pub fn disable_built_in_root_certificates(mut self) -> Self {
412 self.http_settings().disable_built_in_root_certificates = true;
413 self
414 }
415
416 pub fn http_client(mut self, client: reqwest::Client) -> Self {
426 self.http_cfg = Some(HttpConfig::Custom(client));
427 self
428 }
429
430 pub fn server_versions(mut self, value: impl IntoIterator<Item = MatrixVersion>) -> Self {
435 self.server_versions = Some(value.into_iter().collect());
436 self
437 }
438
439 #[cfg(not(target_family = "wasm"))]
440 fn http_settings(&mut self) -> &mut HttpSettings {
441 self.http_cfg.get_or_insert_with(Default::default).settings()
442 }
443
444 pub fn handle_refresh_tokens(mut self) -> Self {
466 self.handle_refresh_tokens = true;
467 self
468 }
469
470 #[doc(hidden)]
472 pub fn base_client(mut self, base_client: BaseClient) -> Self {
473 self.base_client = Some(base_client);
474 self
475 }
476
477 #[cfg(feature = "e2e-encryption")]
480 pub fn with_encryption_settings(mut self, settings: EncryptionSettings) -> Self {
481 self.encryption_settings = settings;
482 self
483 }
484
485 #[cfg(feature = "e2e-encryption")]
488 pub fn with_room_key_recipient_strategy(mut self, strategy: CollectStrategy) -> Self {
489 self.room_key_recipient_strategy = strategy;
490 self
491 }
492
493 #[cfg(feature = "e2e-encryption")]
495 pub fn with_decryption_settings(mut self, decryption_settings: DecryptionSettings) -> Self {
496 self.decryption_settings = decryption_settings;
497 self
498 }
499
500 #[cfg(feature = "e2e-encryption")]
508 pub fn with_enable_share_history_on_invite(
509 mut self,
510 enable_share_history_on_invite: bool,
511 ) -> Self {
512 self.enable_share_history_on_invite = enable_share_history_on_invite;
513 self
514 }
515
516 pub fn cross_process_store_config(
526 mut self,
527 cross_process_store_config: CrossProcessLockConfig,
528 ) -> Self {
529 self.cross_process_lock_config = cross_process_store_config;
530 self
531 }
532
533 pub fn with_threading_support(mut self, threading_support: ThreadingSupport) -> Self {
537 self.threading_support = threading_support;
538 self
539 }
540
541 #[cfg(feature = "experimental-search")]
543 pub fn search_index_store(mut self, kind: SearchIndexStoreKind) -> Self {
544 self.search_index_store_kind = kind;
545 self
546 }
547
548 #[instrument(skip_all, target = "matrix_sdk::client", fields(homeserver))]
561 pub async fn build(self) -> Result<Client, ClientBuildError> {
562 debug!("Starting to build the Client");
563
564 let homeserver_cfg = self.homeserver_cfg.ok_or(ClientBuildError::MissingHomeserver)?;
565 Span::current().record("homeserver", debug(&homeserver_cfg));
566
567 #[cfg_attr(target_family = "wasm", allow(clippy::infallible_destructuring_match))]
568 let inner_http_client = match self.http_cfg.unwrap_or_default() {
569 #[cfg(not(target_family = "wasm"))]
570 HttpConfig::Settings(mut settings) => {
571 settings.timeout = self.request_config.timeout;
572 settings.make_client()?
573 }
574 HttpConfig::Custom(c) => c,
575 };
576
577 let base_client = if let Some(base_client) = self.base_client {
578 base_client
579 } else {
580 #[allow(unused_mut)]
581 let mut client = BaseClient::new(
582 build_store_config(self.store_config, &self.cross_process_lock_config).await?,
583 self.threading_support,
584 self.dm_room_definition,
585 );
586
587 #[cfg(feature = "e2e-encryption")]
588 {
589 client.room_key_recipient_strategy = self.room_key_recipient_strategy;
590 client.decryption_settings = self.decryption_settings;
591 }
592
593 client
594 };
595
596 let http_client = HttpClient::new(inner_http_client.clone(), self.request_config);
597
598 #[allow(unused_variables)]
599 let HomeserverDiscoveryResult { server, homeserver, supported_versions, well_known } =
600 homeserver_cfg.discover(&http_client).await?;
601
602 let sliding_sync_version = {
603 let supported_versions = match supported_versions {
604 Some(versions) => Some(versions),
605 None if self.sliding_sync_version_builder.needs_get_supported_versions() => {
606 Some(get_supported_versions(&homeserver, &http_client).await?)
607 }
608 None => None,
609 };
610
611 let version = self.sliding_sync_version_builder.build(
612 supported_versions.map(|response| response.as_supported_versions()).as_ref(),
613 )?;
614
615 tracing::info!(?version, "selected sliding sync version");
616
617 version
618 };
619
620 let allow_insecure_oauth = homeserver.scheme() == "http";
621 let auth_ctx = Arc::new(AuthCtx::new(self.handle_refresh_tokens, allow_insecure_oauth));
622
623 let send_queue = Arc::new(SendQueueData::new(true));
625
626 let supported_versions = match self.server_versions {
627 Some(versions) => Cached(TtlValue::without_expiry(SupportedVersions {
628 versions,
629 features: Default::default(),
630 })),
631 None => NotSet,
632 };
633 let well_known = match well_known {
634 Some(well_known) => Cached(TtlValue::new(Some(well_known.into()))),
635 None => NotSet,
636 };
637
638 let event_cache = OnceCell::new();
639 let latest_events = OnceCell::new();
640 let thread_subscriptions_catchup = OnceCell::new();
641
642 #[cfg(feature = "experimental-search")]
643 let search_index =
644 SearchIndex::new(Arc::new(Mutex::new(HashMap::new())), self.search_index_store_kind);
645
646 let inner = ClientInner::new(
647 auth_ctx,
648 server,
649 homeserver,
650 sliding_sync_version,
651 http_client,
652 base_client,
653 supported_versions,
654 well_known,
655 self.respect_login_well_known,
656 event_cache,
657 send_queue,
658 latest_events,
659 #[cfg(feature = "e2e-encryption")]
660 self.encryption_settings,
661 #[cfg(feature = "e2e-encryption")]
662 self.enable_share_history_on_invite,
663 self.cross_process_lock_config,
664 #[cfg(feature = "experimental-search")]
665 search_index,
666 thread_subscriptions_catchup,
667 )
668 .await;
669
670 debug!("Done building the Client");
671
672 Ok(Client { inner })
673 }
674}
675
676pub fn sanitize_server_name(s: &str) -> crate::Result<OwnedServerName, IdParseError> {
680 ServerName::parse(
681 s.trim().trim_start_matches("http://").trim_start_matches("https://").trim_end_matches('/'),
682 )
683}
684
685#[allow(clippy::unused_async, unused)] async fn build_store_config(
687 builder_config: BuilderStoreConfig,
688 cross_process_store_config: &CrossProcessLockConfig,
689) -> Result<StoreConfig, ClientBuildError> {
690 #[allow(clippy::infallible_destructuring_match)]
691 let store_config = match builder_config {
692 #[cfg(feature = "sqlite")]
693 BuilderStoreConfig::Sqlite { config, cache_path } => {
694 let config_with_cache_path = if let Some(ref cache_path) = cache_path {
695 config.clone().path(cache_path)
696 } else {
697 config.clone()
698 };
699
700 #[cfg(feature = "e2e-encryption")]
701 let (state_store, event_cache_store, media_store, crypto_store) = try_join!(
702 matrix_sdk_sqlite::SqliteStateStore::open_with_config(&config),
703 matrix_sdk_sqlite::SqliteEventCacheStore::open_with_config(&config_with_cache_path),
704 matrix_sdk_sqlite::SqliteMediaStore::open_with_config(&config_with_cache_path),
705 matrix_sdk_sqlite::SqliteCryptoStore::open_with_config(&config),
706 )?;
707 #[cfg(not(feature = "e2e-encryption"))]
708 let (state_store, event_cache_store, media_store) = try_join!(
709 matrix_sdk_sqlite::SqliteStateStore::open_with_config(&config),
710 matrix_sdk_sqlite::SqliteEventCacheStore::open_with_config(&config_with_cache_path),
711 matrix_sdk_sqlite::SqliteMediaStore::open_with_config(&config),
712 )?;
713 let store_config = StoreConfig::new(cross_process_store_config.clone())
714 .state_store(state_store)
715 .event_cache_store(event_cache_store)
716 .media_store(media_store);
717
718 #[cfg(feature = "e2e-encryption")]
719 let store_config = store_config.crypto_store(crypto_store);
720
721 store_config
722 }
723
724 #[cfg(feature = "indexeddb")]
725 BuilderStoreConfig::IndexedDb { name, passphrase } => {
726 build_indexeddb_store_config(
727 &name,
728 passphrase.as_deref(),
729 cross_process_store_config.clone(),
730 )
731 .await?
732 }
733
734 BuilderStoreConfig::Custom(config) => config,
735 };
736 Ok(store_config)
737}
738
739#[cfg(all(target_family = "wasm", feature = "indexeddb"))]
742async fn build_indexeddb_store_config(
743 name: &str,
744 passphrase: Option<&str>,
745 cross_process_store_config: CrossProcessLockConfig,
746) -> Result<StoreConfig, ClientBuildError> {
747 let stores = matrix_sdk_indexeddb::IndexeddbStores::open(name, passphrase).await?;
748 let store_config = StoreConfig::new(cross_process_store_config)
749 .state_store(stores.state)
750 .event_cache_store(stores.event_cache)
751 .media_store(stores.media);
752
753 #[cfg(feature = "e2e-encryption")]
754 let store_config = store_config.crypto_store(stores.crypto);
755
756 Ok(store_config)
757}
758
759#[cfg(all(not(target_family = "wasm"), feature = "indexeddb"))]
760#[allow(clippy::unused_async)]
761async fn build_indexeddb_store_config(
762 _name: &str,
763 _passphrase: Option<&str>,
764 _cross_process_store_config: CrossProcessLockConfig,
765) -> Result<StoreConfig, ClientBuildError> {
766 panic!("the IndexedDB is only available on the 'wasm32' arch")
767}
768
769#[derive(Clone, Debug)]
770enum HttpConfig {
771 #[cfg(not(target_family = "wasm"))]
772 Settings(HttpSettings),
773 Custom(reqwest::Client),
774}
775
776#[cfg(not(target_family = "wasm"))]
777impl HttpConfig {
778 fn settings(&mut self) -> &mut HttpSettings {
779 match self {
780 Self::Settings(s) => s,
781 Self::Custom(_) => {
782 *self = Self::default();
783 match self {
784 Self::Settings(s) => s,
785 Self::Custom(_) => unreachable!(),
786 }
787 }
788 }
789 }
790}
791
792impl Default for HttpConfig {
793 fn default() -> Self {
794 #[cfg(not(target_family = "wasm"))]
795 return Self::Settings(HttpSettings::default());
796
797 #[cfg(target_family = "wasm")]
798 return Self::Custom(reqwest::Client::new());
799 }
800}
801
802#[derive(Clone)]
803enum BuilderStoreConfig {
804 #[cfg(feature = "sqlite")]
805 Sqlite {
806 config: SqliteStoreConfig,
807 cache_path: Option<PathBuf>,
808 },
809 #[cfg(feature = "indexeddb")]
810 IndexedDb {
811 name: String,
812 passphrase: Option<String>,
813 },
814 Custom(StoreConfig),
815}
816
817#[cfg(not(tarpaulin_include))]
818impl fmt::Debug for BuilderStoreConfig {
819 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
820 #[allow(clippy::infallible_destructuring_match)]
821 match self {
822 #[cfg(feature = "sqlite")]
823 Self::Sqlite { config, cache_path, .. } => f
824 .debug_struct("Sqlite")
825 .field("config", config)
826 .field("cache_path", cache_path)
827 .finish_non_exhaustive(),
828
829 #[cfg(feature = "indexeddb")]
830 Self::IndexedDb { name, .. } => {
831 f.debug_struct("IndexedDb").field("name", name).finish_non_exhaustive()
832 }
833
834 Self::Custom(store_config) => f.debug_tuple("Custom").field(store_config).finish(),
835 }
836 }
837}
838
839#[derive(Debug, Error)]
841pub enum ClientBuildError {
842 #[error("No homeserver or user ID was configured")]
844 MissingHomeserver,
845
846 #[error("The supplied server name is invalid")]
848 InvalidServerName,
849
850 #[error("Error looking up the .well-known endpoint on auto-discovery")]
852 AutoDiscovery(FromHttpResponseError<RumaApiError>),
853
854 #[error(transparent)]
856 SlidingSyncVersion(#[from] crate::sliding_sync::VersionBuilderError),
857
858 #[error(transparent)]
860 Url(#[from] url::ParseError),
861
862 #[error(transparent)]
864 Http(#[from] HttpError),
865
866 #[cfg(feature = "indexeddb")]
868 #[error(transparent)]
869 IndexeddbStore(#[from] matrix_sdk_indexeddb::OpenStoreError),
870
871 #[cfg(feature = "sqlite")]
873 #[error(transparent)]
874 SqliteStore(#[from] matrix_sdk_sqlite::OpenStoreError),
875}
876
877#[cfg(all(test, not(target_family = "wasm")))]
879pub(crate) mod tests {
880 use assert_matches::assert_matches;
881 use assert_matches2::assert_let;
882 use matrix_sdk_test::{async_test, test_json};
883 use serde_json::{Value as JsonValue, json_internal};
884 use wiremock::{
885 Mock, MockServer, ResponseTemplate,
886 matchers::{method, path},
887 };
888
889 use super::*;
890 use crate::sliding_sync::Version as SlidingSyncVersion;
891
892 #[test]
893 fn test_sanitize_server_name() {
894 assert_eq!(sanitize_server_name("matrix.org").unwrap().as_str(), "matrix.org");
895 assert_eq!(sanitize_server_name("https://matrix.org").unwrap().as_str(), "matrix.org");
896 assert_eq!(sanitize_server_name("http://matrix.org").unwrap().as_str(), "matrix.org");
897 assert_eq!(
898 sanitize_server_name("https://matrix.server.org").unwrap().as_str(),
899 "matrix.server.org"
900 );
901 assert_eq!(
902 sanitize_server_name("https://matrix.server.org/").unwrap().as_str(),
903 "matrix.server.org"
904 );
905 assert_eq!(
906 sanitize_server_name(" https://matrix.server.org// ").unwrap().as_str(),
907 "matrix.server.org"
908 );
909 assert_matches!(sanitize_server_name("https://matrix.server.org/something"), Err(_))
910 }
911
912 #[async_test]
919 async fn test_discovery_invalid_server() {
920 let mut builder = ClientBuilder::new();
922
923 builder = builder.server_name_or_homeserver_url("⚠️ This won't work 🚫");
925 let error = builder.build().await.unwrap_err();
926
927 assert_matches!(error, ClientBuildError::InvalidServerName);
929 }
930
931 #[async_test]
932 async fn test_discovery_no_server() {
933 let mut builder = ClientBuilder::new();
935
936 builder = builder.server_name_or_homeserver_url("localhost:3456");
938 let error = builder.build().await.unwrap_err();
939
940 println!("{error}");
942 assert_matches!(error, ClientBuildError::Http(_));
943 }
944
945 #[async_test]
946 async fn test_discovery_web_server() {
947 let server = MockServer::start().await;
950 let mut builder = ClientBuilder::new();
951
952 builder = builder.server_name_or_homeserver_url(server.uri());
954 let error = builder.build().await.unwrap_err();
955
956 assert_matches!(error, ClientBuildError::AutoDiscovery(FromHttpResponseError::Server(_)));
958 }
959
960 #[async_test]
961 async fn test_discovery_direct_legacy() {
962 let homeserver = make_mock_homeserver().await;
964 let mut builder = ClientBuilder::new();
965
966 builder = builder.server_name_or_homeserver_url(homeserver.uri());
968 let _client = builder.build().await.unwrap();
969
970 assert!(_client.sliding_sync_version().is_native());
972 }
973
974 #[async_test]
975 async fn test_discovery_well_known_parse_error() {
976 let server = MockServer::start().await;
978 let homeserver = make_mock_homeserver().await;
979 let mut builder = ClientBuilder::new();
980
981 let well_known = make_well_known_json(&homeserver.uri());
982 let bad_json = well_known.to_string().replace(',', "");
983 Mock::given(method("GET"))
984 .and(path("/.well-known/matrix/client"))
985 .respond_with(ResponseTemplate::new(200).set_body_json(bad_json))
986 .mount(&server)
987 .await;
988
989 builder = builder.server_name_or_homeserver_url(server.uri());
991 let error = builder.build().await.unwrap_err();
992
993 assert_matches!(
995 error,
996 ClientBuildError::AutoDiscovery(FromHttpResponseError::Deserialization(_))
997 );
998 }
999
1000 #[async_test]
1001 async fn test_discovery_well_known_legacy() {
1002 let server = MockServer::start().await;
1005 let homeserver = make_mock_homeserver().await;
1006 let mut builder = ClientBuilder::new();
1007
1008 Mock::given(method("GET"))
1009 .and(path("/.well-known/matrix/client"))
1010 .respond_with(
1011 ResponseTemplate::new(200).set_body_json(make_well_known_json(&homeserver.uri())),
1012 )
1013 .mount(&server)
1014 .await;
1015
1016 builder = builder.server_name_or_homeserver_url(server.uri());
1018 let client = builder.build().await.unwrap();
1019
1020 assert!(client.sliding_sync_version().is_native());
1023 }
1024
1025 #[async_test]
1026 async fn test_sliding_sync_discover_native() {
1027 let homeserver = make_mock_homeserver().await;
1029 let mut builder = ClientBuilder::new();
1030
1031 builder = builder
1034 .server_name_or_homeserver_url(homeserver.uri())
1035 .sliding_sync_version_builder(SlidingSyncVersionBuilder::DiscoverNative);
1036
1037 let client = builder.build().await.unwrap();
1038
1039 assert_matches!(client.sliding_sync_version(), SlidingSyncVersion::Native);
1041 }
1042
1043 #[async_test]
1044 #[cfg(feature = "e2e-encryption")]
1045 async fn test_set_up_decryption_trust_requirement_cross_signed() {
1046 let homeserver = make_mock_homeserver().await;
1047 let builder = ClientBuilder::new()
1048 .server_name_or_homeserver_url(homeserver.uri())
1049 .with_decryption_settings(DecryptionSettings {
1050 sender_device_trust_requirement: TrustRequirement::CrossSigned,
1051 });
1052
1053 let client = builder.build().await.unwrap();
1054 assert_matches!(
1055 client.base_client().decryption_settings.sender_device_trust_requirement,
1056 TrustRequirement::CrossSigned
1057 );
1058 }
1059
1060 #[async_test]
1061 #[cfg(feature = "e2e-encryption")]
1062 async fn test_set_up_decryption_trust_requirement_untrusted() {
1063 let homeserver = make_mock_homeserver().await;
1064
1065 let builder = ClientBuilder::new()
1066 .server_name_or_homeserver_url(homeserver.uri())
1067 .with_decryption_settings(DecryptionSettings {
1068 sender_device_trust_requirement: TrustRequirement::Untrusted,
1069 });
1070
1071 let client = builder.build().await.unwrap();
1072 assert_matches!(
1073 client.base_client().decryption_settings.sender_device_trust_requirement,
1074 TrustRequirement::Untrusted
1075 );
1076 }
1077
1078 async fn make_mock_homeserver() -> MockServer {
1081 let homeserver = MockServer::start().await;
1082 Mock::given(method("GET"))
1083 .and(path("/_matrix/client/versions"))
1084 .respond_with(ResponseTemplate::new(200).set_body_json(&*test_json::VERSIONS))
1085 .mount(&homeserver)
1086 .await;
1087 Mock::given(method("GET"))
1088 .and(path("/_matrix/client/r0/login"))
1089 .respond_with(ResponseTemplate::new(200).set_body_json(&*test_json::LOGIN_TYPES))
1090 .mount(&homeserver)
1091 .await;
1092 homeserver
1093 }
1094
1095 fn make_well_known_json(homeserver_url: &str) -> JsonValue {
1096 ::serde_json::Value::Object({
1097 let mut object = ::serde_json::Map::new();
1098 let _ = object.insert(
1099 "m.homeserver".into(),
1100 json_internal!({
1101 "base_url": homeserver_url
1102 }),
1103 );
1104
1105 object
1106 })
1107 }
1108
1109 #[async_test]
1110 async fn test_cross_process_store_locks_holder_name() {
1111 {
1112 let homeserver = make_mock_homeserver().await;
1113 let client =
1114 ClientBuilder::new().homeserver_url(homeserver.uri()).build().await.unwrap();
1115
1116 assert_let!(
1117 CrossProcessLockConfig::MultiProcess { holder_name } =
1118 client.cross_process_lock_config()
1119 );
1120 assert_eq!(holder_name, "main");
1121 }
1122
1123 {
1124 let homeserver = make_mock_homeserver().await;
1125 let client = ClientBuilder::new()
1126 .homeserver_url(homeserver.uri())
1127 .cross_process_store_config(CrossProcessLockConfig::multi_process("foo"))
1128 .build()
1129 .await
1130 .unwrap();
1131
1132 assert_let!(
1133 CrossProcessLockConfig::MultiProcess { holder_name } =
1134 client.cross_process_lock_config()
1135 );
1136 assert_eq!(holder_name, "foo");
1137 }
1138 }
1139}