ruma_client_api/discovery/
get_authorization_server_metadata.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
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! `GET /_matrix/client/*/auth_metadata`
//!
//! Get the metadata of the authorization server that is trusted by the homeserver.

mod serde;

pub mod msc2965 {
    //! `MSC2965` ([MSC])
    //!
    //! [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2965

    use std::collections::BTreeSet;

    use ruma_common::{
        api::{request, response, Metadata},
        metadata,
        serde::{OrdAsRefStr, PartialEqAsRefStr, PartialOrdAsRefStr, Raw, StringEnum},
    };
    use serde::Serialize;
    use url::Url;

    use crate::PrivOwnedStr;

    const METADATA: Metadata = metadata! {
        method: GET,
        rate_limited: false,
        authentication: None,
        history: {
            unstable => "/_matrix/client/unstable/org.matrix.msc2965/auth_metadata",
        }
    };

    /// Request type for the `auth_metadata` endpoint.
    #[request(error = crate::Error)]
    #[derive(Default)]
    pub struct Request {}

    /// Request type for the `auth_metadata` endpoint.
    #[response(error = crate::Error)]
    pub struct Response {
        /// The authorization server metadata as defined in [RFC8414].
        ///
        /// [RFC8414]: https://datatracker.ietf.org/doc/html/rfc8414
        #[ruma_api(body)]
        pub metadata: Raw<AuthorizationServerMetadata>,
    }

    impl Request {
        /// Creates a new empty `Request`.
        pub fn new() -> Self {
            Self {}
        }
    }

    impl Response {
        /// Creates a new `Response` with the given serialized authorization server metadata.
        pub fn new(metadata: Raw<AuthorizationServerMetadata>) -> Self {
            Self { metadata }
        }
    }

    /// Metadata describing the configuration of the authorization server.
    ///
    /// While the metadata properties and their values are declared for OAuth 2.0 in [RFC8414] and
    /// other RFCs, this type only supports properties and values that are used for Matrix, as
    /// specified in [MSC3861] and its dependencies.
    ///
    /// This type is validated to have at least all the required values during deserialization. The
    /// URLs are not validated during deserialization, to validate them use
    /// [`AuthorizationServerMetadata::validate_urls()`] or
    /// [`AuthorizationServerMetadata::insecure_validate_urls()`].
    ///
    /// This type has no constructor, it should be sent as raw JSON directly.
    ///
    /// [RFC8414]: https://datatracker.ietf.org/doc/html/rfc8414
    /// [MSC3861]: https://github.com/matrix-org/matrix-spec-proposals/pull/3861
    #[derive(Debug, Clone, Serialize)]
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    pub struct AuthorizationServerMetadata {
        /// The authorization server's issuer identifier.
        ///
        /// This should be a URL with no query or fragment components.
        pub issuer: Url,

        /// URL of the authorization server's authorization endpoint ([RFC6749]).
        ///
        /// [RFC6749]: https://datatracker.ietf.org/doc/html/rfc6749
        pub authorization_endpoint: Url,

        /// URL of the authorization server's token endpoint ([RFC6749]).
        ///
        /// [RFC6749]: https://datatracker.ietf.org/doc/html/rfc6749
        pub token_endpoint: Url,

        /// URL of the authorization server's OAuth 2.0 Dynamic Client Registration endpoint
        /// ([RFC7591]).
        ///
        /// [RFC7591]: https://datatracker.ietf.org/doc/html/rfc7591
        #[serde(skip_serializing_if = "Option::is_none")]
        pub registration_endpoint: Option<Url>,

        /// List of the OAuth 2.0 `response_type` values that this authorization server supports.
        ///
        /// Those values are the same as those used with the `response_types` parameter defined by
        /// OAuth 2.0 Dynamic Client Registration ([RFC7591]).
        ///
        /// This field must include [`ResponseType::Code`].
        ///
        /// [RFC7591]: https://datatracker.ietf.org/doc/html/rfc7591
        pub response_types_supported: BTreeSet<ResponseType>,

        /// List of the OAuth 2.0 `response_mode` values that this authorization server supports.
        ///
        /// Those values are specified in [OAuth 2.0 Multiple Response Type Encoding Practices].
        ///
        /// This field must include [`ResponseMode::Query`] and [`ResponseMode::Fragment`].
        ///
        /// [OAuth 2.0 Multiple Response Type Encoding Practices]: https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html
        pub response_modes_supported: BTreeSet<ResponseMode>,

        /// List of the OAuth 2.0 `grant_type` values that this authorization server supports.
        ///
        /// Those values are the same as those used with the `grant_types` parameter defined by
        /// OAuth 2.0 Dynamic Client Registration ([RFC7591]).
        ///
        /// This field must include [`GrantType::AuthorizationCode`] and
        /// [`GrantType::RefreshToken`].
        ///
        /// [RFC7591]: https://datatracker.ietf.org/doc/html/rfc7591
        pub grant_types_supported: BTreeSet<GrantType>,

        /// URL of the authorization server's OAuth 2.0 revocation endpoint ([RFC7009]).
        ///
        /// [RFC7009]: https://datatracker.ietf.org/doc/html/rfc7009
        pub revocation_endpoint: Url,

        /// List of Proof Key for Code Exchange (PKCE) code challenge methods supported by this
        /// authorization server ([RFC7636]).
        ///
        /// This field must include [`CodeChallengeMethod::S256`].
        ///
        /// [RFC7636]: https://datatracker.ietf.org/doc/html/rfc7636
        pub code_challenge_methods_supported: BTreeSet<CodeChallengeMethod>,

        /// URL where the user is able to access the account management capabilities of the
        /// authorization server ([MSC4191]).
        ///
        /// [MSC4191]: https://github.com/matrix-org/matrix-spec-proposals/pull/4191
        #[serde(skip_serializing_if = "Option::is_none")]
        pub account_management_uri: Option<Url>,

        /// List of actions that the account management URL supports ([MSC4191]).
        ///
        /// [MSC4191]: https://github.com/matrix-org/matrix-spec-proposals/pull/4191
        #[serde(skip_serializing_if = "BTreeSet::is_empty")]
        pub account_management_actions_supported: BTreeSet<AccountManagementAction>,

        /// URL of the authorization server's device authorization endpoint ([RFC8628]).
        ///
        /// [RFC8628]: https://datatracker.ietf.org/doc/html/rfc8628
        #[serde(skip_serializing_if = "Option::is_none")]
        pub device_authorization_endpoint: Option<Url>,

        /// The [`Prompt`] values supported by the authorization server ([Initiating User
        /// Registration via OpenID Connect 1.0]).
        ///
        /// [Initiating User Registration via OpenID Connect 1.0]: https://openid.net/specs/openid-connect-prompt-create-1_0.html
        #[serde(skip_serializing_if = "Vec::is_empty")]
        pub prompt_values_supported: Vec<Prompt>,
    }

    impl AuthorizationServerMetadata {
        /// Strict validation of the URLs in this `AuthorizationServerMetadata`.
        ///
        /// This checks that:
        ///
        /// * The `issuer` is a valid URL using an `https` scheme and without a query or fragment.
        ///
        /// * All the URLs use an `https` scheme.
        pub fn validate_urls(&self) -> Result<(), AuthorizationServerMetadataUrlError> {
            self.validate_urls_inner(false)
        }

        /// Weak validation the URLs `AuthorizationServerMetadata` are all absolute URLs.
        ///
        /// This only checks that the `issuer` is a valid URL without a query or fragment.
        ///
        /// In production, you should prefer [`AuthorizationServerMetadata`] that also check if the
        /// URLs use an `https` scheme. This method is meant for development purposes, when
        /// interacting with a local authorization server.
        pub fn insecure_validate_urls(&self) -> Result<(), AuthorizationServerMetadataUrlError> {
            self.validate_urls_inner(true)
        }

        /// Get an iterator over the URLs of this `AuthorizationServerMetadata`, except the
        /// `issuer`.
        fn validate_urls_inner(
            &self,
            insecure: bool,
        ) -> Result<(), AuthorizationServerMetadataUrlError> {
            if self.issuer.query().is_some() || self.issuer.fragment().is_some() {
                return Err(AuthorizationServerMetadataUrlError::IssuerHasQueryOrFragment);
            }

            if insecure {
                // No more checks.
                return Ok(());
            }

            let required_urls = &[
                ("issuer", &self.issuer),
                ("authorization_endpoint", &self.authorization_endpoint),
                ("token_endpoint", &self.token_endpoint),
                ("revocation_endpoint", &self.revocation_endpoint),
            ];
            let optional_urls = &[
                self.registration_endpoint.as_ref().map(|string| ("registration_endpoint", string)),
                self.account_management_uri
                    .as_ref()
                    .map(|string| ("account_management_uri", string)),
                self.device_authorization_endpoint
                    .as_ref()
                    .map(|string| ("device_authorization_endpoint", string)),
            ];

            for (field, url) in required_urls.iter().chain(optional_urls.iter().flatten()) {
                if url.scheme() != "https" {
                    return Err(AuthorizationServerMetadataUrlError::NotHttpsScheme(field));
                }
            }

            Ok(())
        }
    }

    /// The method to use at the authorization endpoint.
    #[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
    #[derive(Clone, StringEnum, PartialEqAsRefStr, Eq, PartialOrdAsRefStr, OrdAsRefStr)]
    #[ruma_enum(rename_all = "lowercase")]
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    pub enum ResponseType {
        /// Use the authorization code grant flow ([RFC6749]).
        ///
        /// [RFC6749]: https://datatracker.ietf.org/doc/html/rfc6749
        Code,

        #[doc(hidden)]
        _Custom(PrivOwnedStr),
    }

    /// The mechanism to be used for returning authorization response parameters from the
    /// authorization endpoint.
    ///
    /// The values are specified in [OAuth 2.0 Multiple Response Type Encoding Practices].
    #[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
    ///
    /// [OAuth 2.0 Multiple Response Type Encoding Practices]: https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html
    #[derive(Clone, StringEnum, PartialEqAsRefStr, Eq, PartialOrdAsRefStr, OrdAsRefStr)]
    #[ruma_enum(rename_all = "lowercase")]
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    pub enum ResponseMode {
        /// Authorization Response parameters are encoded in the fragment added to the
        /// `redirect_uri` when redirecting back to the client.
        Query,

        /// Authorization Response parameters are encoded in the query string added to the
        /// `redirect_uri` when redirecting back to the client.
        Fragment,

        #[doc(hidden)]
        _Custom(PrivOwnedStr),
    }

    /// The grant type to use at the token endpoint.
    #[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
    #[derive(Clone, StringEnum, PartialEqAsRefStr, Eq, PartialOrdAsRefStr, OrdAsRefStr)]
    #[ruma_enum(rename_all = "snake_case")]
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    pub enum GrantType {
        /// The authorization code grant type ([RFC6749]).
        ///
        /// [RFC6749]: https://datatracker.ietf.org/doc/html/rfc6749
        AuthorizationCode,

        /// The refresh token grant type ([RFC6749]).
        ///
        /// [RFC6749]: https://datatracker.ietf.org/doc/html/rfc6749
        RefreshToken,

        /// The device code grant type ([RFC8628]).
        ///
        /// [RFC8628]: https://datatracker.ietf.org/doc/html/rfc8628
        #[cfg(feature = "unstable-msc4108")]
        #[ruma_enum(rename = "urn:ietf:params:oauth:grant-type:device_code")]
        DeviceCode,

        #[doc(hidden)]
        _Custom(PrivOwnedStr),
    }

    /// The code challenge method to use at the authorization endpoint.
    #[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
    #[derive(Clone, StringEnum, PartialEqAsRefStr, Eq, PartialOrdAsRefStr, OrdAsRefStr)]
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    pub enum CodeChallengeMethod {
        /// Use a SHA-256, base64url-encoded code challenge ([RFC7636]).
        ///
        /// [RFC7636]: https://datatracker.ietf.org/doc/html/rfc7636
        S256,

        #[doc(hidden)]
        _Custom(PrivOwnedStr),
    }

    /// The action that the user wishes to do at the account management URL.
    ///
    /// The values are specified in [MSC4191].
    #[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
    ///
    /// [MSC4191]: https://github.com/matrix-org/matrix-spec-proposals/pull/4191
    #[derive(Clone, StringEnum, PartialEqAsRefStr, Eq, PartialOrdAsRefStr, OrdAsRefStr)]
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    pub enum AccountManagementAction {
        /// The user wishes to view their profile (name, avatar, contact details).
        ///
        /// [RFC7636]: https://datatracker.ietf.org/doc/html/rfc7636
        #[ruma_enum(rename = "org.matrix.profile")]
        Profile,

        /// The user wishes to view a list of their sessions.
        #[ruma_enum(rename = "org.matrix.sessions_list")]
        SessionsList,

        /// The user wishes to view the details of a specific session.
        #[ruma_enum(rename = "org.matrix.session_view")]
        SessionView,

        /// The user wishes to end/logout a specific session.
        #[ruma_enum(rename = "org.matrix.session_end")]
        SessionEnd,

        /// The user wishes to deactivate their account.
        #[ruma_enum(rename = "org.matrix.account_deactivate")]
        AccountDeactivate,

        /// The user wishes to reset their cross-signing keys.
        #[ruma_enum(rename = "org.matrix.cross_signing_reset")]
        CrossSigningReset,

        #[doc(hidden)]
        _Custom(PrivOwnedStr),
    }

    /// The possible errors when validating URLs of [`AuthorizationServerMetadata`].
    #[derive(Debug, Clone, thiserror::Error)]
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    pub enum AuthorizationServerMetadataUrlError {
        /// The URL of the field does not use the `https` scheme.
        #[error("URL in `{0}` must use the `https` scheme")]
        NotHttpsScheme(&'static str),

        /// The `issuer` URL has a query or fragment component.
        #[error("URL in `issuer` cannot have a query or fragment component")]
        IssuerHasQueryOrFragment,
    }

    /// The desired user experience when using the authorization endpoint.
    #[derive(Clone, StringEnum, PartialEqAsRefStr, Eq, PartialOrdAsRefStr, OrdAsRefStr)]
    #[ruma_enum(rename_all = "lowercase")]
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    pub enum Prompt {
        /// The user wants to create a new account ([Initiating User Registration via OpenID
        /// Connect 1.0]).
        ///
        /// [Initiating User Registration via OpenID Connect 1.0]: https://openid.net/specs/openid-connect-prompt-create-1_0.html
        Create,

        #[doc(hidden)]
        _Custom(PrivOwnedStr),
    }
}

#[cfg(test)]
mod tests {
    use serde_json::{from_value as from_json_value, json, Value as JsonValue};
    use url::Url;

    use super::msc2965::AuthorizationServerMetadata;

    /// A valid `AuthorizationServerMetadata` with all fields and values, as a JSON object.
    pub(super) fn authorization_server_metadata_json() -> JsonValue {
        json!({
            "issuer": "https://server.local/",
            "authorization_endpoint": "https://server.local/authorize",
            "token_endpoint": "https://server.local/token",
            "registration_endpoint": "https://server.local/register",
            "response_types_supported": ["code"],
            "response_modes_supported": ["query", "fragment"],
            "grant_types_supported": ["authorization_code", "refresh_token"],
            "revocation_endpoint": "https://server.local/revoke",
            "code_challenge_methods_supported": ["S256"],
            "account_management_uri": "https://server.local/account",
            "account_management_actions_supported": [
                "org.matrix.profile",
                "org.matrix.sessions_list",
                "org.matrix.session_view",
                "org.matrix.session_end",
                "org.matrix.account_deactivate",
                "org.matrix.cross_signing_reset",
            ],
            "device_authorization_endpoint": "https://server.local/device",
        })
    }

    /// A valid `AuthorizationServerMetadata`, with valid URLs.
    fn authorization_server_metadata() -> AuthorizationServerMetadata {
        from_json_value(authorization_server_metadata_json()).unwrap()
    }

    #[test]
    fn metadata_valid_urls() {
        let metadata = authorization_server_metadata();
        metadata.validate_urls().unwrap();
        metadata.insecure_validate_urls().unwrap();
    }

    #[test]
    fn metadata_invalid_or_insecure_issuer() {
        let original_metadata = authorization_server_metadata();

        // URL with query string.
        let mut metadata = original_metadata.clone();
        metadata.issuer = Url::parse("https://server.local/?session=1er45elp").unwrap();
        metadata.validate_urls().unwrap_err();
        metadata.insecure_validate_urls().unwrap_err();

        // URL with fragment.
        let mut metadata = original_metadata.clone();
        metadata.issuer = Url::parse("https://server.local/#session").unwrap();
        metadata.validate_urls().unwrap_err();
        metadata.insecure_validate_urls().unwrap_err();

        // Insecure URL.
        let mut metadata = original_metadata;
        metadata.issuer = Url::parse("http://server.local/").unwrap();
        metadata.validate_urls().unwrap_err();
        metadata.insecure_validate_urls().unwrap();
    }

    #[test]
    fn metadata_insecure_urls() {
        let original_metadata = authorization_server_metadata();

        let mut metadata = original_metadata.clone();
        metadata.authorization_endpoint = Url::parse("http://server.local/authorize").unwrap();
        metadata.validate_urls().unwrap_err();
        metadata.insecure_validate_urls().unwrap();

        let mut metadata = original_metadata.clone();
        metadata.token_endpoint = Url::parse("http://server.local/token").unwrap();
        metadata.validate_urls().unwrap_err();
        metadata.insecure_validate_urls().unwrap();

        let mut metadata = original_metadata.clone();
        metadata.registration_endpoint = Some(Url::parse("http://server.local/register").unwrap());
        metadata.validate_urls().unwrap_err();
        metadata.insecure_validate_urls().unwrap();

        let mut metadata = original_metadata.clone();
        metadata.revocation_endpoint = Url::parse("http://server.local/revoke").unwrap();
        metadata.validate_urls().unwrap_err();
        metadata.insecure_validate_urls().unwrap();

        let mut metadata = original_metadata.clone();
        metadata.account_management_uri = Some(Url::parse("http://server.local/account").unwrap());
        metadata.validate_urls().unwrap_err();
        metadata.insecure_validate_urls().unwrap();

        let mut metadata = original_metadata.clone();
        metadata.device_authorization_endpoint =
            Some(Url::parse("http://server.local/device").unwrap());
        metadata.validate_urls().unwrap_err();
        metadata.insecure_validate_urls().unwrap();
    }
}