matrix_sdk/client/builder/
homeserver_config.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Copyright 2024 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use ruma::{
    api::{
        client::discovery::{discover_homeserver, get_supported_versions},
        MatrixVersion,
    },
    OwnedServerName, ServerName,
};
use tracing::debug;
use url::Url;

use crate::{
    config::RequestConfig, http_client::HttpClient, sanitize_server_name, ClientBuildError,
    HttpError,
};

/// Configuration for the homeserver.
#[derive(Clone, Debug)]
pub(super) enum HomeserverConfig {
    /// A homeserver name URL, including the protocol.
    HomeserverUrl(String),

    /// A server name, with the protocol put apart.
    ServerName { server: OwnedServerName, protocol: UrlScheme },

    /// A server name with or without the protocol (it will fallback to `https`
    /// if absent), or a homeserver URL.
    ServerNameOrHomeserverUrl(String),
}

/// A simple helper to represent `http` or `https` in a URL.
#[derive(Clone, Copy, Debug)]
pub(super) enum UrlScheme {
    Http,
    Https,
}

/// The `Ok` result for `HomeserverConfig::discover`.
pub(super) struct HomeserverDiscoveryResult {
    pub server: Option<Url>,
    pub homeserver: Url,
    pub well_known: Option<discover_homeserver::Response>,
    pub supported_versions: Option<get_supported_versions::Response>,
}

impl HomeserverConfig {
    pub async fn discover(
        &self,
        http_client: &HttpClient,
    ) -> Result<HomeserverDiscoveryResult, ClientBuildError> {
        Ok(match self {
            Self::HomeserverUrl(url) => {
                let homeserver = Url::parse(url)?;

                HomeserverDiscoveryResult {
                    server: None, // We can't know the `server` if we only have a `homeserver`.
                    homeserver,
                    well_known: None,
                    supported_versions: None,
                }
            }

            Self::ServerName { server, protocol } => {
                let (server, well_known) =
                    discover_homeserver(server, protocol, http_client).await?;

                HomeserverDiscoveryResult {
                    server: Some(server),
                    homeserver: Url::parse(&well_known.homeserver.base_url)?,
                    well_known: Some(well_known),
                    supported_versions: None,
                }
            }

            Self::ServerNameOrHomeserverUrl(server_name_or_url) => {
                let (server, homeserver, well_known, supported_versions) =
                    discover_homeserver_from_server_name_or_url(
                        server_name_or_url.to_owned(),
                        http_client,
                    )
                    .await?;

                HomeserverDiscoveryResult { server, homeserver, well_known, supported_versions }
            }
        })
    }
}

/// Discovers a homeserver from a server name or a URL.
///
/// Tries well-known discovery and checking if the URL points to a homeserver.
async fn discover_homeserver_from_server_name_or_url(
    mut server_name_or_url: String,
    http_client: &HttpClient,
) -> Result<
    (
        Option<Url>,
        Url,
        Option<discover_homeserver::Response>,
        Option<get_supported_versions::Response>,
    ),
    ClientBuildError,
> {
    let mut discovery_error: Option<ClientBuildError> = None;

    // Attempt discovery as a server name first.
    let sanitize_result = sanitize_server_name(&server_name_or_url);

    if let Ok(server_name) = sanitize_result.as_ref() {
        let protocol = if server_name_or_url.starts_with("http://") {
            UrlScheme::Http
        } else {
            UrlScheme::Https
        };

        match discover_homeserver(server_name, &protocol, http_client).await {
            Ok((server, well_known)) => {
                return Ok((
                    Some(server),
                    Url::parse(&well_known.homeserver.base_url)?,
                    Some(well_known),
                    None,
                ));
            }
            Err(e) => {
                debug!(error = %e, "Well-known discovery failed.");
                discovery_error = Some(e);

                // Check if the server name points to a homeserver.
                server_name_or_url = match protocol {
                    UrlScheme::Http => format!("http://{server_name}"),
                    UrlScheme::Https => format!("https://{server_name}"),
                }
            }
        }
    }

    // When discovery fails, or the input isn't a valid server name, fallback to
    // trying a homeserver URL.
    if let Ok(homeserver_url) = Url::parse(&server_name_or_url) {
        // Make sure the URL is definitely for a homeserver.
        match get_supported_versions(&homeserver_url, http_client).await {
            Ok(response) => {
                return Ok((None, homeserver_url, None, Some(response)));
            }
            Err(e) => {
                debug!(error = %e, "Checking supported versions failed.");
            }
        }
    }

    Err(discovery_error.unwrap_or(ClientBuildError::InvalidServerName))
}

/// Discovers a homeserver by looking up the well-known at the supplied server
/// name.
async fn discover_homeserver(
    server_name: &ServerName,
    protocol: &UrlScheme,
    http_client: &HttpClient,
) -> Result<(Url, discover_homeserver::Response), ClientBuildError> {
    debug!("Trying to discover the homeserver");

    let server = Url::parse(&match protocol {
        UrlScheme::Http => format!("http://{server_name}"),
        UrlScheme::Https => format!("https://{server_name}"),
    })?;

    let well_known = http_client
        .send(
            discover_homeserver::Request::new(),
            Some(RequestConfig::short_retry()),
            server.to_string(),
            None,
            &[MatrixVersion::V1_0],
            Default::default(),
        )
        .await
        .map_err(|e| match e {
            HttpError::Api(err) => ClientBuildError::AutoDiscovery(err),
            err => ClientBuildError::Http(err),
        })?;

    debug!(homeserver_url = well_known.homeserver.base_url, "Discovered the homeserver");

    Ok((server, well_known))
}

pub(super) async fn get_supported_versions(
    homeserver_url: &Url,
    http_client: &HttpClient,
) -> Result<get_supported_versions::Response, HttpError> {
    http_client
        .send(
            get_supported_versions::Request::new(),
            Some(RequestConfig::short_retry()),
            homeserver_url.to_string(),
            None,
            &[MatrixVersion::V1_0],
            Default::default(),
        )
        .await
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use matrix_sdk_test::async_test;
    use ruma::OwnedServerName;
    use serde_json::json;
    use wiremock::{
        matchers::{method, path},
        Mock, MockServer, ResponseTemplate,
    };

    use super::*;
    use crate::http_client::HttpSettings;

    #[async_test]
    async fn test_url() {
        let http_client =
            HttpClient::new(HttpSettings::default().make_client().unwrap(), Default::default());

        let result = HomeserverConfig::HomeserverUrl("https://matrix-client.matrix.org".to_owned())
            .discover(&http_client)
            .await
            .unwrap();

        assert_eq!(result.server, None);
        assert_eq!(result.homeserver, Url::parse("https://matrix-client.matrix.org").unwrap());
        assert!(result.well_known.is_none());
        assert!(result.supported_versions.is_none());
    }

    #[async_test]
    async fn test_server_name() {
        let http_client =
            HttpClient::new(HttpSettings::default().make_client().unwrap(), Default::default());

        let server = MockServer::start().await;
        let homeserver = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/.well-known/matrix/client"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "m.homeserver": {
                    "base_url": homeserver.uri(),
                },
            })))
            .mount(&server)
            .await;

        let result = HomeserverConfig::ServerName {
            server: OwnedServerName::try_from(server.address().to_string()).unwrap(),
            protocol: UrlScheme::Http,
        }
        .discover(&http_client)
        .await
        .unwrap();

        assert_eq!(result.server, Some(Url::parse(&server.uri()).unwrap()));
        assert_eq!(result.homeserver, Url::parse(&homeserver.uri()).unwrap());
        assert!(result.well_known.is_some());
        assert!(result.supported_versions.is_none());
    }

    #[async_test]
    async fn test_server_name_or_url_with_name() {
        let http_client =
            HttpClient::new(HttpSettings::default().make_client().unwrap(), Default::default());

        let server = MockServer::start().await;
        let homeserver = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/.well-known/matrix/client"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "m.homeserver": {
                    "base_url": homeserver.uri(),
                },
            })))
            .mount(&server)
            .await;

        let result = HomeserverConfig::ServerNameOrHomeserverUrl(server.uri().to_string())
            .discover(&http_client)
            .await
            .unwrap();

        assert_eq!(result.server, Some(Url::parse(&server.uri()).unwrap()));
        assert_eq!(result.homeserver, Url::parse(&homeserver.uri()).unwrap());
        assert!(result.well_known.is_some());
        assert!(result.supported_versions.is_none());
    }

    #[async_test]
    async fn test_server_name_or_url_with_url() {
        let http_client =
            HttpClient::new(HttpSettings::default().make_client().unwrap(), Default::default());

        let homeserver = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/_matrix/client/versions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "versions": [],
            })))
            .mount(&homeserver)
            .await;

        let result = HomeserverConfig::ServerNameOrHomeserverUrl(homeserver.uri().to_string())
            .discover(&http_client)
            .await
            .unwrap();

        assert!(result.server.is_none());
        assert_eq!(result.homeserver, Url::parse(&homeserver.uri()).unwrap());
        assert!(result.well_known.is_none());
        assert!(result.supported_versions.is_some());
    }
}