matrix-sdk 0.19.0

A high level Matrix client-server library.
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
// 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::{
    OwnedServerName, ServerName,
    api::client::discovery::{discover_homeserver, get_supported_versions},
};
use tracing::debug;
use url::Url;

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

/// 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 supported_versions: Option<get_supported_versions::Response>,
    pub well_known: Option<discover_homeserver::Response>,
}

impl HomeserverConfig {
    /// Resolve this configuration into a homeserver URL.
    ///
    /// If `well_known_lookup_disabled` is set, no request is ever made to the
    /// `.well-known/matrix/client` URI. [`Self::ServerName`] can then not be
    /// resolved at all, and fails with
    /// [`ClientBuildError::WellKnownLookupDisabled`].
    pub async fn discover(
        &self,
        http_client: &HttpClient,
        well_known_lookup_disabled: bool,
    ) -> 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,
                    supported_versions: None,
                    well_known: None,
                }
            }

            Self::ServerName { server, protocol } => {
                // The well-known is the only source of the homeserver URL here, so there is
                // nothing we could fall back to. Assuming the server name *is* the homeserver
                // would silently talk to the wrong host for any delegating deployment.
                if well_known_lookup_disabled {
                    return Err(ClientBuildError::WellKnownLookupDisabled);
                }

                let (server, well_known) =
                    discover_homeserver(server, protocol, http_client).await?;

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

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

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

/// Discovers a homeserver from a server name or a URL.
///
/// Tries well-known discovery and checking if the URL points to a homeserver.
///
/// If `well_known_lookup_disabled` is set, the well-known discovery step is
/// skipped entirely and only the homeserver URL check is performed.
async fn discover_homeserver_from_server_name_or_url(
    mut server_name_or_url: String,
    http_client: &HttpClient,
    well_known_lookup_disabled: bool,
) -> Result<
    (
        Option<Url>,
        Url,
        Option<get_supported_versions::Response>,
        Option<discover_homeserver::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
        };

        let server_name_as_url = match protocol {
            UrlScheme::Http => format!("http://{server_name}"),
            UrlScheme::Https => format!("https://{server_name}"),
        };

        if well_known_lookup_disabled {
            debug!("Well-known discovery is disabled, checking for a homeserver URL directly.");
            server_name_or_url = server_name_as_url;
        } else {
            match discover_homeserver(server_name, &protocol, http_client).await {
                Ok((server, well_known)) => {
                    return Ok((
                        Some(server),
                        Url::parse(&well_known.homeserver.base_url)?,
                        None,
                        Some(well_known),
                    ));
                }
                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 = server_name_as_url;
                }
            }
        }
    }

    // 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, Some(response), None));
            }
            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,
            (),
            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,
            (),
            Default::default(),
        )
        .await
}

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

    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, false)
            .await
            .unwrap();

        assert_eq!(result.server, None);
        assert_eq!(result.homeserver, Url::parse("https://matrix-client.matrix.org").unwrap());
        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, false)
        .await
        .unwrap();

        assert_eq!(result.server, Some(Url::parse(&server.uri()).unwrap()));
        assert_eq!(result.homeserver, Url::parse(&homeserver.uri()).unwrap());
        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, false)
            .await
            .unwrap();

        assert_eq!(result.server, Some(Url::parse(&server.uri()).unwrap()));
        assert_eq!(result.homeserver, Url::parse(&homeserver.uri()).unwrap());
        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, false)
            .await
            .unwrap();

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

    /// Mounts a well-known mock that must never be hit. `MockServer` verifies
    /// the expectation when it is dropped, at the end of the test.
    async fn mock_well_known_never_called(server: &MockServer, homeserver: &MockServer) {
        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(),
                },
            })))
            .named("well-known mock")
            .expect(0)
            .mount(server)
            .await;
    }

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

        // A homeserver URL never needs a lookup, so the flag changes nothing.
        let result = HomeserverConfig::HomeserverUrl("https://matrix-client.matrix.org".to_owned())
            .discover(&http_client, true)
            .await
            .unwrap();

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

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

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

        mock_well_known_never_called(&server, &homeserver).await;

        // A server name can only be resolved through the well-known, so this must fail
        // rather than guess a homeserver.
        let error = HomeserverConfig::ServerName {
            server: OwnedServerName::try_from(server.address().to_string()).unwrap(),
            protocol: UrlScheme::Http,
        }
        .discover(&http_client, true)
        .await
        .err()
        .unwrap();

        assert_matches!(error, ClientBuildError::WellKnownLookupDisabled);
    }

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

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

        mock_well_known_never_called(&server, &homeserver).await;

        // The value points at a delegating server, not at a homeserver: with the
        // well-known step skipped, the homeserver check is all that's left, and it
        // fails since `server` doesn't answer `/_matrix/client/versions`.
        let error = HomeserverConfig::ServerNameOrHomeserverUrl(server.uri().to_string())
            .discover(&http_client, true)
            .await
            .err()
            .unwrap();

        assert_matches!(error, ClientBuildError::InvalidServerName);
    }

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

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

        mock_well_known_never_called(&homeserver, &homeserver).await;

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

        // The value points at a homeserver, which the `/_matrix/client/versions` check
        // proves, so this resolves without ever touching the well-known.
        let result = HomeserverConfig::ServerNameOrHomeserverUrl(homeserver.uri().to_string())
            .discover(&http_client, true)
            .await
            .unwrap();

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