1use 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#[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
79pub(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 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#[derive(Debug, Clone, Deserialize)]
150pub struct ClientRegistrationResponse {
151 pub client_id: ClientId,
153
154 pub client_id_issued_at: Option<SecondsSinceUnixEpoch>,
156}
157
158#[derive(Debug, Clone, Serialize)]
171#[serde(into = "ClientMetadataSerializeHelper")]
172pub struct ClientMetadata {
173 pub application_type: ApplicationType,
175
176 pub grant_types: Vec<OAuthGrantType>,
180
181 pub client_uri: Localized<Url>,
183
184 pub client_name: Option<Localized<String>>,
186
187 pub logo_uri: Option<Localized<Url>>,
189
190 pub policy_uri: Option<Localized<Url>>,
193
194 pub tos_uri: Option<Localized<Url>>,
197}
198
199impl ClientMetadata {
200 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#[derive(Debug, Clone)]
224#[non_exhaustive]
225pub enum OAuthGrantType {
226 AuthorizationCode {
233 redirect_uris: Vec<Url>,
235 },
236
237 DeviceCode,
246}
247
248#[derive(Clone, StringEnum)]
250#[ruma_enum(rename_all = "lowercase")]
251#[non_exhaustive]
252pub enum ApplicationType {
253 Web,
258
259 Native,
263
264 #[doc(hidden)]
265 _Custom(PrivOwnedStr),
266}
267
268#[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 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 pub fn non_localized(&self) -> &T {
286 &self.non_localized
287 }
288
289 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 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 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
367struct 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 let client_uri = Localized::new(
438 Url::parse("https://github.com/matrix-org/matrix-rust-sdk").unwrap(),
439 [],
440 );
441
442 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 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 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}