Skip to main content

matrix_sdk/authentication/oauth/
registration.rs

1// Copyright 2025 Kévin Commaille
2// Copyright 2026 Nordeck IT + Consulting GmbH <info@nordeck.net>
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Types and functions for OAuth 2.0 Dynamic Client Registration ([RFC 7591]).
17//!
18//! [RFC 7591]: http://tools.ietf.org/html/rfc7591
19
20use std::collections::{BTreeSet, HashMap};
21
22pub use language_tags;
23use language_tags::LanguageTag;
24use matrix_sdk_base::deserialized_responses::PrivOwnedStr;
25use oauth2::{AsyncHttpClient, ClientId, HttpClientError, RequestTokenError};
26use ruma::{
27    SecondsSinceUnixEpoch,
28    api::client::discovery::get_authorization_server_metadata::v1::{GrantType, ResponseType},
29    serde::{Raw, StringEnum},
30};
31use serde::{Deserialize, Serialize, ser::SerializeMap};
32use url::Url;
33
34use super::{
35    OAuthHttpClient,
36    error::OAuthClientRegistrationError,
37    http_client::{check_http_response_json_content_type, check_http_response_status_code},
38};
39
40/// Register a client with an OAuth 2.0 authorization server.
41///
42/// # Arguments
43///
44/// - `http_service` - The service to use for making HTTP requests.
45/// - `registration_endpoint` - The URL of the issuer's Registration endpoint.
46/// - `client_metadata` - The metadata to register with the issuer.
47/// - `software_statement` - A JWT that asserts metadata values about the client
48///   software that should be signed.
49///
50/// # Errors
51///
52/// Returns an error if the request fails or the response is invalid.
53#[tracing::instrument(skip_all, fields(registration_endpoint))]
54pub(super) async fn register_client(
55    http_client: &OAuthHttpClient,
56    registration_endpoint: &Url,
57    client_metadata: &Raw<ClientMetadata>,
58) -> Result<ClientRegistrationResponse, OAuthClientRegistrationError> {
59    tracing::debug!("Registering client...");
60
61    let body =
62        serde_json::to_vec(client_metadata).map_err(OAuthClientRegistrationError::IntoJson)?;
63    let request = http::Request::post(registration_endpoint.as_str())
64        .header(http::header::CONTENT_TYPE, mime::APPLICATION_JSON.to_string())
65        .body(body)
66        .map_err(|err| RequestTokenError::Request(HttpClientError::Http(err)))?;
67
68    let response = http_client.call(request).await.map_err(RequestTokenError::Request)?;
69
70    check_http_response_status_code(&response)?;
71    check_http_response_json_content_type(&response)?;
72
73    let response = serde_json::from_slice(&response.into_body())
74        .map_err(OAuthClientRegistrationError::FromJson)?;
75
76    Ok(response)
77}
78
79/// Make sure that the given client metadata declares the given grant type in
80/// its `grant_types` field, adding it if necessary.
81///
82/// If the `grant_types` field is missing, it is set to the default value
83/// according to [RFC 7591], i.e. `authorization_code`, and the given grant
84/// type.
85///
86/// If the metadata cannot be deserialized as a JSON object, or if its
87/// `grant_types` field is not an array, it is returned unchanged.
88///
89/// [RFC 7591]: https://datatracker.ietf.org/doc/html/rfc7591#section-2
90pub(super) fn ensure_grant_type(
91    client_metadata: &Raw<ClientMetadata>,
92    grant_type: GrantType,
93) -> Raw<ClientMetadata> {
94    let mut metadata = match client_metadata
95        .deserialize_as_unchecked::<serde_json::Map<String, serde_json::Value>>()
96    {
97        Ok(metadata) => metadata,
98        Err(error) => {
99            tracing::warn!(
100                "Could not add grant type to client metadata that is not a JSON object: {error}"
101            );
102            return client_metadata.clone();
103        }
104    };
105
106    let grant_type = serde_json::Value::from(grant_type.as_str());
107
108    match metadata.get_mut("grant_types") {
109        Some(serde_json::Value::Array(grant_types)) => {
110            if grant_types.contains(&grant_type) {
111                return client_metadata.clone();
112            }
113
114            grant_types.push(grant_type);
115        }
116        Some(_) => {
117            // RFC 7591 requires `grant_types` to be an array, so the metadata
118            // is invalid. We forward it unchanged, and let the
119            // authorization server either reject it during
120            // registration, or accept it leniently.
121            tracing::warn!(
122                "Could not add grant type to client metadata whose `grant_types` is not an array"
123            );
124            return client_metadata.clone();
125        }
126        None => {
127            metadata.insert(
128                "grant_types".to_owned(),
129                vec![serde_json::Value::from(GrantType::AuthorizationCode.as_str()), grant_type]
130                    .into(),
131            );
132        }
133    }
134
135    match serde_json::value::to_raw_value(&metadata) {
136        Ok(json) => Raw::from_json(json),
137        Err(error) => {
138            tracing::warn!(
139                "Could not serialize client metadata with the added grant type: {error}"
140            );
141            client_metadata.clone()
142        }
143    }
144}
145
146/// A successful response to OAuth 2.0 Dynamic Client Registration ([RFC 7591]).
147///
148/// [RFC 7591]: http://tools.ietf.org/html/rfc7591
149#[derive(Debug, Clone, Deserialize)]
150pub struct ClientRegistrationResponse {
151    /// The ID issued for the client by the authorization server.
152    pub client_id: ClientId,
153
154    /// The timestamp at which the client identifier was issued.
155    pub client_id_issued_at: Option<SecondsSinceUnixEpoch>,
156}
157
158/// The metadata necessary to register a client with an OAuth 2.0 authorization
159/// server.
160///
161/// This is a simplified type, designed to avoid inconsistencies between fields.
162/// Only the fields defined in [MSC2966] can be set with this type, and only if
163/// different values are supported by this API. To set other fields, use your
164/// own type or construct directly the JSON representation.
165///
166/// The original format is defined in [RFC 7591].
167///
168/// [MSC2966]: https://github.com/matrix-org/matrix-spec-proposals/pull/2966
169/// [RFC 7591]: https://datatracker.ietf.org/doc/html/rfc7591
170#[derive(Debug, Clone, Serialize)]
171#[serde(into = "ClientMetadataSerializeHelper")]
172pub struct ClientMetadata {
173    /// The type of the application.
174    pub application_type: ApplicationType,
175
176    /// The grant types that the client will use at the token endpoint.
177    ///
178    /// This should match the login methods that the client can use.
179    pub grant_types: Vec<OAuthGrantType>,
180
181    /// URL of the home page of the client.
182    pub client_uri: Localized<Url>,
183
184    /// Name of the client to be presented to the end-user during authorization.
185    pub client_name: Option<Localized<String>>,
186
187    /// URL that references a logo for the client application.
188    pub logo_uri: Option<Localized<Url>>,
189
190    /// URL that the client provides to the end-user to read about the how the
191    /// profile data will be used.
192    pub policy_uri: Option<Localized<Url>>,
193
194    /// URL that the client provides to the end-user to read about the client's
195    /// terms of service.
196    pub tos_uri: Option<Localized<Url>>,
197}
198
199impl ClientMetadata {
200    /// Construct a `ClientMetadata` with only the required fields.
201    pub fn new(
202        application_type: ApplicationType,
203        grant_types: Vec<OAuthGrantType>,
204        client_uri: Localized<Url>,
205    ) -> Self {
206        Self {
207            application_type,
208            grant_types,
209            client_uri,
210            client_name: None,
211            logo_uri: None,
212            policy_uri: None,
213            tos_uri: None,
214        }
215    }
216}
217
218/// The grant types that the user will use at the token endpoint.
219///
220/// The available variants match the methods supported by the [`OAuth`] API.
221///
222/// [`OAuth`]: super::OAuth
223#[derive(Debug, Clone)]
224#[non_exhaustive]
225pub enum OAuthGrantType {
226    /// The authorization code grant type, defined in [RFC 6749].
227    ///
228    /// This grant type is necessary to use [`OAuth::login()`].
229    ///
230    /// [RFC 6749]: https://datatracker.ietf.org/doc/html/rfc6749
231    /// [`OAuth::login()`]: super::OAuth::login
232    AuthorizationCode {
233        /// Redirection URIs for the authorization endpoint.
234        redirect_uris: Vec<Url>,
235    },
236
237    /// The device authorization grant, defined in [RFC 8628].
238    ///
239    /// This grant type is necessary to use [`OAuth::login_with_device_code()`]
240    /// and [`OAuth::login_with_qr_code()`].
241    ///
242    /// [RFC 8628]: https://datatracker.ietf.org/doc/html/rfc8628
243    /// [`OAuth::login_with_device_code()`]: super::OAuth::login_with_device_code
244    /// [`OAuth::login_with_qr_code()`]: super::OAuth::login_with_qr_code
245    DeviceCode,
246}
247
248/// The possible types of an application.
249#[derive(Clone, StringEnum)]
250#[ruma_enum(rename_all = "lowercase")]
251#[non_exhaustive]
252pub enum ApplicationType {
253    /// The application is a web client.
254    ///
255    /// This is a client executed within a user-agent on the device used by the
256    /// user.
257    Web,
258
259    /// The application is a native client.
260    ///
261    /// This is a client installed and executed on the device used by the user.
262    Native,
263
264    #[doc(hidden)]
265    _Custom(PrivOwnedStr),
266}
267
268/// A collection of localized variants.
269///
270/// Always includes one non-localized variant.
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub struct Localized<T> {
273    non_localized: T,
274    localized: HashMap<LanguageTag, T>,
275}
276
277impl<T> Localized<T> {
278    /// Constructs a new `Localized` with the given non-localized and localized
279    /// variants.
280    pub fn new(non_localized: T, localized: impl IntoIterator<Item = (LanguageTag, T)>) -> Self {
281        Self { non_localized, localized: localized.into_iter().collect() }
282    }
283
284    /// Get the non-localized variant.
285    pub fn non_localized(&self) -> &T {
286        &self.non_localized
287    }
288
289    /// Get the variant corresponding to the given language, if it exists.
290    pub fn get(&self, language: Option<&LanguageTag>) -> Option<&T> {
291        match language {
292            Some(lang) => self.localized.get(lang),
293            None => Some(&self.non_localized),
294        }
295    }
296}
297
298impl<T> From<(T, HashMap<LanguageTag, T>)> for Localized<T> {
299    fn from(t: (T, HashMap<LanguageTag, T>)) -> Self {
300        Localized { non_localized: t.0, localized: t.1 }
301    }
302}
303
304#[derive(Serialize)]
305struct ClientMetadataSerializeHelper {
306    #[serde(skip_serializing_if = "Vec::is_empty")]
307    redirect_uris: Vec<Url>,
308    token_endpoint_auth_method: &'static str,
309    grant_types: BTreeSet<GrantType>,
310    #[serde(skip_serializing_if = "Vec::is_empty")]
311    response_types: Vec<ResponseType>,
312    application_type: ApplicationType,
313    #[serde(flatten)]
314    localized: ClientMetadataLocalizedFields,
315}
316
317impl From<ClientMetadata> for ClientMetadataSerializeHelper {
318    fn from(value: ClientMetadata) -> Self {
319        let ClientMetadata {
320            application_type,
321            grant_types: oauth_grant_types,
322            client_uri,
323            client_name,
324            logo_uri,
325            policy_uri,
326            tos_uri,
327        } = value;
328
329        let mut redirect_uris = None;
330        let mut response_types = None;
331        let mut grant_types = BTreeSet::new();
332
333        // Support for refresh tokens is mandatory.
334        grant_types.insert(GrantType::RefreshToken);
335
336        for oauth_grant_type in oauth_grant_types {
337            match oauth_grant_type {
338                OAuthGrantType::AuthorizationCode { redirect_uris: uris } => {
339                    redirect_uris = Some(uris);
340                    response_types = Some(vec![ResponseType::Code]);
341                    grant_types.insert(GrantType::AuthorizationCode);
342                }
343                OAuthGrantType::DeviceCode => {
344                    grant_types.insert(GrantType::DeviceCode);
345                }
346            }
347        }
348
349        ClientMetadataSerializeHelper {
350            redirect_uris: redirect_uris.unwrap_or_default(),
351            // We only support public clients.
352            token_endpoint_auth_method: "none",
353            grant_types,
354            response_types: response_types.unwrap_or_default(),
355            application_type,
356            localized: ClientMetadataLocalizedFields {
357                client_uri,
358                client_name,
359                logo_uri,
360                policy_uri,
361                tos_uri,
362            },
363        }
364    }
365}
366
367/// Helper type for serialization of `Localized` fields.
368///
369/// Those fields require to be serialized as one field per language so we need
370/// to use a custom `Serialize` implementation.
371struct ClientMetadataLocalizedFields {
372    client_uri: Localized<Url>,
373    client_name: Option<Localized<String>>,
374    logo_uri: Option<Localized<Url>>,
375    policy_uri: Option<Localized<Url>>,
376    tos_uri: Option<Localized<Url>>,
377}
378
379impl Serialize for ClientMetadataLocalizedFields {
380    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
381    where
382        S: serde::Serializer,
383    {
384        fn serialize_localized_into_map<M: SerializeMap, T: Serialize>(
385            map: &mut M,
386            field_name: &str,
387            value: &Localized<T>,
388        ) -> Result<(), M::Error> {
389            map.serialize_entry(field_name, &value.non_localized)?;
390
391            for (lang, localized) in &value.localized {
392                map.serialize_entry(&format!("{field_name}#{lang}"), localized)?;
393            }
394
395            Ok(())
396        }
397
398        let mut map = serializer.serialize_map(None)?;
399
400        serialize_localized_into_map(&mut map, "client_uri", &self.client_uri)?;
401
402        if let Some(client_name) = &self.client_name {
403            serialize_localized_into_map(&mut map, "client_name", client_name)?;
404        }
405
406        if let Some(logo_uri) = &self.logo_uri {
407            serialize_localized_into_map(&mut map, "logo_uri", logo_uri)?;
408        }
409
410        if let Some(policy_uri) = &self.policy_uri {
411            serialize_localized_into_map(&mut map, "policy_uri", policy_uri)?;
412        }
413
414        if let Some(tos_uri) = &self.tos_uri {
415            serialize_localized_into_map(&mut map, "tos_uri", tos_uri)?;
416        }
417
418        map.end()
419    }
420}
421
422#[cfg(test)]
423mod tests {
424    use language_tags::LanguageTag;
425    use ruma::{
426        api::client::discovery::get_authorization_server_metadata::v1::GrantType, serde::Raw,
427    };
428    use serde_json::json;
429    use url::Url;
430
431    use super::{ApplicationType, ClientMetadata, Localized, OAuthGrantType, ensure_grant_type};
432
433    #[test]
434    fn test_ensure_grant_type() {
435        // Ensure that a grant type is added to the client metadata only when it
436        // is missing, without changing the other fields.
437        let client_uri = Localized::new(
438            Url::parse("https://github.com/matrix-org/matrix-rust-sdk").unwrap(),
439            [],
440        );
441
442        // The grant type is added if it is missing.
443        let metadata = Raw::new(&ClientMetadata::new(
444            ApplicationType::Native,
445            vec![OAuthGrantType::AuthorizationCode {
446                redirect_uris: vec![Url::parse("http://127.0.0.1/").unwrap()],
447            }],
448            client_uri.clone(),
449        ))
450        .unwrap();
451        let metadata = ensure_grant_type(&metadata, GrantType::DeviceCode);
452        assert_eq!(
453            metadata.get_field::<Vec<String>>("grant_types").unwrap().unwrap(),
454            ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code"]
455        );
456        assert_eq!(
457            metadata.get_field::<Vec<String>>("redirect_uris").unwrap().unwrap(),
458            ["http://127.0.0.1/"]
459        );
460
461        // The grant type is not duplicated if it is already present.
462        let metadata = Raw::new(&ClientMetadata::new(
463            ApplicationType::Native,
464            vec![OAuthGrantType::DeviceCode],
465            client_uri,
466        ))
467        .unwrap();
468        let metadata = ensure_grant_type(&metadata, GrantType::DeviceCode);
469        assert_eq!(
470            metadata.get_field::<Vec<String>>("grant_types").unwrap().unwrap(),
471            ["refresh_token", "urn:ietf:params:oauth:grant-type:device_code"]
472        );
473
474        // The default value is used if the field is missing.
475        let metadata = Raw::new(&json!({ "application_type": "native" })).unwrap().cast_unchecked();
476        let metadata = ensure_grant_type(&metadata, GrantType::DeviceCode);
477        assert_eq!(
478            metadata.get_field::<Vec<String>>("grant_types").unwrap().unwrap(),
479            ["authorization_code", "urn:ietf:params:oauth:grant-type:device_code"]
480        );
481    }
482
483    #[test]
484    fn test_serialize_minimal_client_metadata() {
485        let metadata = ClientMetadata::new(
486            ApplicationType::Native,
487            vec![OAuthGrantType::AuthorizationCode {
488                redirect_uris: vec![Url::parse("http://127.0.0.1/").unwrap()],
489            }],
490            Localized::new(
491                Url::parse("https://github.com/matrix-org/matrix-rust-sdk").unwrap(),
492                [],
493            ),
494        );
495
496        assert_eq!(
497            serde_json::to_value(metadata).unwrap(),
498            json!({
499                "application_type": "native",
500                "grant_types": ["authorization_code", "refresh_token"],
501                "response_types": ["code"],
502                "token_endpoint_auth_method": "none",
503                "redirect_uris": ["http://127.0.0.1/"],
504                "client_uri": "https://github.com/matrix-org/matrix-rust-sdk",
505            }),
506        );
507    }
508
509    #[test]
510    fn test_serialize_full_client_metadata() {
511        let lang_fr = LanguageTag::parse("fr").unwrap();
512        let lang_mas = LanguageTag::parse("mas").unwrap();
513
514        let mut metadata = ClientMetadata::new(
515            ApplicationType::Web,
516            vec![
517                OAuthGrantType::AuthorizationCode {
518                    redirect_uris: vec![
519                        Url::parse("http://127.0.0.1/").unwrap(),
520                        Url::parse("http://[::1]/").unwrap(),
521                    ],
522                },
523                OAuthGrantType::DeviceCode,
524            ],
525            Localized::new(
526                Url::parse("https://example.org/matrix-client").unwrap(),
527                [
528                    (lang_fr.clone(), Url::parse("https://example.org/fr/matrix-client").unwrap()),
529                    (
530                        lang_mas.clone(),
531                        Url::parse("https://example.org/mas/matrix-client").unwrap(),
532                    ),
533                ],
534            ),
535        );
536
537        metadata.client_name = Some(Localized::new(
538            "My Matrix client".to_owned(),
539            [(lang_fr.clone(), "Mon client Matrix".to_owned())],
540        ));
541        metadata.logo_uri =
542            Some(Localized::new(Url::parse("https://example.org/logo.svg").unwrap(), []));
543        metadata.policy_uri = Some(Localized::new(
544            Url::parse("https://example.org/policy").unwrap(),
545            [
546                (lang_fr.clone(), Url::parse("https://example.org/fr/policy").unwrap()),
547                (lang_mas.clone(), Url::parse("https://example.org/mas/policy").unwrap()),
548            ],
549        ));
550        metadata.tos_uri = Some(Localized::new(
551            Url::parse("https://example.org/tos").unwrap(),
552            [
553                (lang_fr, Url::parse("https://example.org/fr/tos").unwrap()),
554                (lang_mas, Url::parse("https://example.org/mas/tos").unwrap()),
555            ],
556        ));
557
558        assert_eq!(
559            serde_json::to_value(metadata).unwrap(),
560            json!({
561                "application_type": "web",
562                "grant_types": [
563                    "authorization_code",
564                    "refresh_token",
565                    "urn:ietf:params:oauth:grant-type:device_code",
566                ],
567                "response_types": ["code"],
568                "token_endpoint_auth_method": "none",
569                "redirect_uris": ["http://127.0.0.1/", "http://[::1]/"],
570                "client_uri": "https://example.org/matrix-client",
571                "client_uri#fr": "https://example.org/fr/matrix-client",
572                "client_uri#mas": "https://example.org/mas/matrix-client",
573                "client_name": "My Matrix client",
574                "client_name#fr": "Mon client Matrix",
575                "logo_uri": "https://example.org/logo.svg",
576                "policy_uri": "https://example.org/policy",
577                "policy_uri#fr": "https://example.org/fr/policy",
578                "policy_uri#mas": "https://example.org/mas/policy",
579                "tos_uri": "https://example.org/tos",
580                "tos_uri#fr": "https://example.org/fr/tos",
581                "tos_uri#mas": "https://example.org/mas/tos",
582            }),
583        );
584    }
585}