ruma_client_api/session/
get_login_types.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
//! `GET /_matrix/client/*/login`
//!
//! Gets the homeserver's supported login types to authenticate users. Clients should pick one of
//! these and supply it as the type when logging in.

pub mod v3 {
    //! `/v3/` ([spec])
    //!
    //! [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3login

    use std::borrow::Cow;

    use ruma_common::{
        api::{request, response, Metadata},
        metadata,
        serde::{JsonObject, StringEnum},
        OwnedMxcUri,
    };
    use serde::{de::DeserializeOwned, Deserialize, Serialize};
    use serde_json::Value as JsonValue;

    use crate::PrivOwnedStr;

    const METADATA: Metadata = metadata! {
        method: GET,
        rate_limited: true,
        authentication: None,
        history: {
            1.0 => "/_matrix/client/r0/login",
            1.1 => "/_matrix/client/v3/login",
        }
    };

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

    /// Response type for the `get_login_types` endpoint.
    #[response(error = crate::Error)]
    pub struct Response {
        /// The homeserver's supported login types.
        pub flows: Vec<LoginType>,
    }

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

    impl Response {
        /// Creates a new `Response` with the given login types.
        pub fn new(flows: Vec<LoginType>) -> Self {
            Self { flows }
        }
    }

    /// An authentication mechanism.
    #[derive(Clone, Debug, Serialize)]
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    #[serde(untagged)]
    pub enum LoginType {
        /// A password is supplied to authenticate.
        Password(PasswordLoginType),

        /// Token-based login.
        Token(TokenLoginType),

        /// SSO-based login.
        Sso(SsoLoginType),

        /// Application Service login.
        ApplicationService(ApplicationServiceLoginType),

        /// Custom login type.
        #[doc(hidden)]
        _Custom(Box<CustomLoginType>),
    }

    impl LoginType {
        /// Creates a new `LoginType` with the given `login_type` string and data.
        ///
        /// Prefer to use the public variants of `LoginType` where possible; this constructor is
        /// meant be used for unsupported login types only and does not allow setting
        /// arbitrary data for supported ones.
        pub fn new(login_type: &str, data: JsonObject) -> serde_json::Result<Self> {
            fn from_json_object<T: DeserializeOwned>(obj: JsonObject) -> serde_json::Result<T> {
                serde_json::from_value(JsonValue::Object(obj))
            }

            Ok(match login_type {
                "m.login.password" => Self::Password(from_json_object(data)?),
                "m.login.token" => Self::Token(from_json_object(data)?),
                "m.login.sso" => Self::Sso(from_json_object(data)?),
                "m.login.application_service" => Self::ApplicationService(from_json_object(data)?),
                _ => {
                    Self::_Custom(Box::new(CustomLoginType { type_: login_type.to_owned(), data }))
                }
            })
        }

        /// Returns a reference to the `login_type` string.
        pub fn login_type(&self) -> &str {
            match self {
                Self::Password(_) => "m.login.password",
                Self::Token(_) => "m.login.token",
                Self::Sso(_) => "m.login.sso",
                Self::ApplicationService(_) => "m.login.application_service",
                Self::_Custom(c) => &c.type_,
            }
        }

        /// Returns the associated data.
        ///
        /// Prefer to use the public variants of `LoginType` where possible; this method is meant to
        /// be used for unsupported login types only.
        pub fn data(&self) -> Cow<'_, JsonObject> {
            fn serialize<T: Serialize>(obj: &T) -> JsonObject {
                match serde_json::to_value(obj).expect("login type serialization to succeed") {
                    JsonValue::Object(obj) => obj,
                    _ => panic!("all login types must serialize to objects"),
                }
            }

            match self {
                Self::Password(d) => Cow::Owned(serialize(d)),
                Self::Token(d) => Cow::Owned(serialize(d)),
                Self::Sso(d) => Cow::Owned(serialize(d)),
                Self::ApplicationService(d) => Cow::Owned(serialize(d)),
                Self::_Custom(c) => Cow::Borrowed(&c.data),
            }
        }
    }

    /// The payload for password login.
    #[derive(Clone, Debug, Default, Deserialize, Serialize)]
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    #[serde(tag = "type", rename = "m.login.password")]
    pub struct PasswordLoginType {}

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

    /// The payload for token-based login.
    #[derive(Clone, Debug, Default, Deserialize, Serialize)]
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    #[serde(tag = "type", rename = "m.login.token")]
    pub struct TokenLoginType {
        /// Whether the homeserver supports the `POST /login/get_token` endpoint.
        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
        pub get_login_token: bool,
    }

    impl TokenLoginType {
        /// Creates a new `TokenLoginType`.
        pub fn new() -> Self {
            Self { get_login_token: false }
        }
    }

    /// The payload for SSO login.
    #[derive(Clone, Debug, Default, Deserialize, Serialize)]
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    #[serde(tag = "type", rename = "m.login.sso")]
    pub struct SsoLoginType {
        /// The identity provider choices.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        pub identity_providers: Vec<IdentityProvider>,
    }

    impl SsoLoginType {
        /// Creates a new `SsoLoginType`.
        pub fn new() -> Self {
            Self::default()
        }
    }

    /// An SSO login identity provider.
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    #[derive(Clone, Debug, Deserialize, Serialize)]
    pub struct IdentityProvider {
        /// The ID of the provider.
        pub id: String,

        /// The display name of the provider.
        pub name: String,

        /// The icon for the provider.
        pub icon: Option<OwnedMxcUri>,

        /// The brand identifier for the provider.
        pub brand: Option<IdentityProviderBrand>,
    }

    impl IdentityProvider {
        /// Creates an `IdentityProvider` with the given `id` and `name`.
        pub fn new(id: String, name: String) -> Self {
            Self { id, name, icon: None, brand: None }
        }
    }

    /// An SSO login identity provider brand identifier.
    ///
    /// The predefined ones can be found in the matrix-spec-proposals repo in a [separate
    /// document][matrix-spec-proposals].
    ///
    /// [matrix-spec-proposals]: https://github.com/matrix-org/matrix-spec-proposals/blob/v1.1/informal/idp-brands.md
    #[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
    #[derive(Clone, PartialEq, Eq, StringEnum)]
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    pub enum IdentityProviderBrand {
        /// The [Apple] brand.
        ///
        /// [Apple]: https://developer.apple.com/design/human-interface-guidelines/sign-in-with-apple/overview/buttons/
        #[ruma_enum(rename = "apple")]
        Apple,

        /// The [Facebook](https://developers.facebook.com/docs/facebook-login/web/login-button/) brand.
        #[ruma_enum(rename = "facebook")]
        Facebook,

        /// The [GitHub](https://github.com/logos) brand.
        #[ruma_enum(rename = "github")]
        GitHub,

        /// The [GitLab](https://about.gitlab.com/press/press-kit/) brand.
        #[ruma_enum(rename = "gitlab")]
        GitLab,

        /// The [Google](https://developers.google.com/identity/branding-guidelines) brand.
        #[ruma_enum(rename = "google")]
        Google,

        /// The [Twitter] brand.
        ///
        /// [Twitter]: https://developer.twitter.com/en/docs/authentication/guides/log-in-with-twitter#tab1
        #[ruma_enum(rename = "twitter")]
        Twitter,

        /// A custom brand.
        #[doc(hidden)]
        _Custom(PrivOwnedStr),
    }

    /// The payload for Application Service login.
    #[derive(Clone, Debug, Default, Deserialize, Serialize)]
    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
    #[serde(tag = "type", rename = "m.login.application_service")]
    pub struct ApplicationServiceLoginType {}

    impl ApplicationServiceLoginType {
        /// Creates a new `ApplicationServiceLoginType`.
        pub fn new() -> Self {
            Self::default()
        }
    }

    /// A custom login payload.
    #[doc(hidden)]
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[allow(clippy::exhaustive_structs)]
    pub struct CustomLoginType {
        /// A custom type
        ///
        /// This field is named `type_` instead of `type` because the latter is a reserved
        /// keyword in Rust.
        #[serde(rename = "type")]
        pub type_: String,

        /// Remaining type content
        #[serde(flatten)]
        pub data: JsonObject,
    }

    mod login_type_serde {
        use ruma_common::serde::from_raw_json_value;
        use serde::{de, Deserialize};
        use serde_json::value::RawValue as RawJsonValue;

        use super::LoginType;

        /// Helper struct to determine the type from a `serde_json::value::RawValue`
        #[derive(Debug, Deserialize)]
        struct LoginTypeDeHelper {
            /// The login type field
            #[serde(rename = "type")]
            type_: String,
        }

        impl<'de> Deserialize<'de> for LoginType {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: de::Deserializer<'de>,
            {
                let json = Box::<RawJsonValue>::deserialize(deserializer)?;
                let LoginTypeDeHelper { type_ } = from_raw_json_value(&json)?;

                Ok(match type_.as_ref() {
                    "m.login.password" => Self::Password(from_raw_json_value(&json)?),
                    "m.login.token" => Self::Token(from_raw_json_value(&json)?),
                    "m.login.sso" => Self::Sso(from_raw_json_value(&json)?),
                    "m.login.application_service" => {
                        Self::ApplicationService(from_raw_json_value(&json)?)
                    }
                    _ => Self::_Custom(from_raw_json_value(&json)?),
                })
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use assert_matches2::assert_matches;
        use ruma_common::mxc_uri;
        use serde::{Deserialize, Serialize};
        use serde_json::{
            from_value as from_json_value, json, to_value as to_json_value, Value as JsonValue,
        };

        use super::{
            IdentityProvider, IdentityProviderBrand, LoginType, SsoLoginType, TokenLoginType,
        };

        #[derive(Debug, Deserialize, Serialize)]
        struct Wrapper {
            flows: Vec<LoginType>,
        }

        #[test]
        fn deserialize_password_login_type() {
            let wrapper = from_json_value::<Wrapper>(json!({
                "flows": [
                    { "type": "m.login.password" }
                ],
            }))
            .unwrap();
            assert_eq!(wrapper.flows.len(), 1);
            assert_matches!(&wrapper.flows[0], LoginType::Password(_));
        }

        #[test]
        fn deserialize_custom_login_type() {
            let wrapper = from_json_value::<Wrapper>(json!({
                "flows": [
                    {
                        "type": "io.ruma.custom",
                        "color": "green",
                    }
                ],
            }))
            .unwrap();
            assert_eq!(wrapper.flows.len(), 1);
            assert_matches!(&wrapper.flows[0], LoginType::_Custom(custom));
            assert_eq!(custom.type_, "io.ruma.custom");
            assert_eq!(custom.data.len(), 1);
            assert_eq!(custom.data.get("color"), Some(&JsonValue::from("green")));
        }

        #[test]
        fn deserialize_sso_login_type() {
            let wrapper = from_json_value::<Wrapper>(json!({
                "flows": [
                    {
                        "type": "m.login.sso",
                        "identity_providers": [
                            {
                                "id": "oidc-gitlab",
                                "name": "GitLab",
                                "icon": "mxc://localhost/gitlab-icon",
                                "brand": "gitlab"
                            },
                            {
                                "id": "custom",
                                "name": "Custom",
                            }
                        ]
                    }
                ],
            }))
            .unwrap();
            assert_eq!(wrapper.flows.len(), 1);
            let flow = &wrapper.flows[0];

            assert_matches!(flow, LoginType::Sso(SsoLoginType { identity_providers }));
            assert_eq!(identity_providers.len(), 2);

            let provider = &identity_providers[0];
            assert_eq!(provider.id, "oidc-gitlab");
            assert_eq!(provider.name, "GitLab");
            assert_eq!(provider.icon.as_deref(), Some(mxc_uri!("mxc://localhost/gitlab-icon")));
            assert_eq!(provider.brand, Some(IdentityProviderBrand::GitLab));

            let provider = &identity_providers[1];
            assert_eq!(provider.id, "custom");
            assert_eq!(provider.name, "Custom");
            assert_eq!(provider.icon, None);
            assert_eq!(provider.brand, None);
        }

        #[test]
        fn serialize_sso_login_type() {
            let wrapper = to_json_value(Wrapper {
                flows: vec![
                    LoginType::Token(TokenLoginType::new()),
                    LoginType::Sso(SsoLoginType {
                        identity_providers: vec![IdentityProvider {
                            id: "oidc-github".into(),
                            name: "GitHub".into(),
                            icon: Some("mxc://localhost/github-icon".into()),
                            brand: Some(IdentityProviderBrand::GitHub),
                        }],
                    }),
                ],
            })
            .unwrap();

            assert_eq!(
                wrapper,
                json!({
                    "flows": [
                        {
                            "type": "m.login.token"
                        },
                        {
                            "type": "m.login.sso",
                            "identity_providers": [
                                {
                                    "id": "oidc-github",
                                    "name": "GitHub",
                                    "icon": "mxc://localhost/github-icon",
                                    "brand": "github"
                                },
                            ]
                        }
                    ],
                })
            );
        }
    }
}