1use std::{borrow::Cow, fmt, time::Duration};
2
3use js_int::UInt;
4use ruma_common::serde::JsonObject;
5use serde::{
6 de::{self, Deserialize, Deserializer, MapAccess, Visitor},
7 ser::{self, Serialize, SerializeMap, Serializer},
8};
9#[cfg(feature = "unstable-msc4363")]
10use serde_json::Value as JsonValue;
11use serde_json::{from_value as from_json_value, map::Entry};
12
13use super::{
14 BadStatusErrorData, CustomErrorKind, ErrorCode, ErrorKind, IncompatibleRoomVersionErrorData,
15 LimitExceededErrorData, ResourceLimitExceededErrorData, RetryAfter, UnknownTokenErrorData,
16 UserLimitExceededErrorData, WrongRoomKeysVersionErrorData,
17};
18#[cfg(feature = "unstable-msc4363")]
19use crate::api::{OAuthClientScope, error::InsufficientUserAuthenticationErrorData};
20#[cfg(feature = "unstable-msc4406")]
21use crate::{OwnedUserId, api::error::SenderIgnoredErrorData};
22
23enum Field<'de> {
24 ErrorCode,
25 SoftLogout,
26 RetryAfterMs,
27 RoomVersion,
28 AdminContact,
29 Status,
30 Body,
31 CurrentVersion,
32 InfoUri,
33 CanUpgrade,
34 #[cfg(feature = "unstable-msc4406")]
35 Sender,
36 #[cfg(feature = "unstable-msc4363")]
37 AcrValues,
38 #[cfg(feature = "unstable-msc4363")]
39 MaxAge,
40 #[cfg(feature = "unstable-msc4363")]
41 Scope,
42 Other(Cow<'de, str>),
43}
44
45impl<'de> Field<'de> {
46 fn new(s: Cow<'de, str>) -> Field<'de> {
47 match s.as_ref() {
48 "errcode" => Self::ErrorCode,
49 "soft_logout" => Self::SoftLogout,
50 "retry_after_ms" => Self::RetryAfterMs,
51 "room_version" => Self::RoomVersion,
52 "admin_contact" => Self::AdminContact,
53 "status" => Self::Status,
54 "body" => Self::Body,
55 "current_version" => Self::CurrentVersion,
56 "info_uri" => Self::InfoUri,
57 "can_upgrade" => Self::CanUpgrade,
58 #[cfg(feature = "unstable-msc4406")]
59 "sender" => Self::Sender,
60 #[cfg(feature = "unstable-msc4363")]
61 "org.matrix.msc4363.acr_values" => Self::AcrValues,
62 #[cfg(feature = "unstable-msc4363")]
63 "org.matrix.msc4363.max_age" => Self::MaxAge,
64 #[cfg(feature = "unstable-msc4363")]
65 "org.matrix.msc4363.scope" => Self::Scope,
66 _ => Self::Other(s),
67 }
68 }
69}
70
71impl<'de> Deserialize<'de> for Field<'de> {
72 fn deserialize<D>(deserializer: D) -> Result<Field<'de>, D::Error>
73 where
74 D: Deserializer<'de>,
75 {
76 struct FieldVisitor;
77
78 impl<'de> Visitor<'de> for FieldVisitor {
79 type Value = Field<'de>;
80
81 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
82 formatter.write_str("any struct field")
83 }
84
85 fn visit_str<E>(self, value: &str) -> Result<Field<'de>, E>
86 where
87 E: de::Error,
88 {
89 Ok(Field::new(Cow::Owned(value.to_owned())))
90 }
91
92 fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Field<'de>, E>
93 where
94 E: de::Error,
95 {
96 Ok(Field::new(Cow::Borrowed(value)))
97 }
98
99 fn visit_string<E>(self, value: String) -> Result<Field<'de>, E>
100 where
101 E: de::Error,
102 {
103 Ok(Field::new(Cow::Owned(value)))
104 }
105 }
106
107 deserializer.deserialize_identifier(FieldVisitor)
108 }
109}
110
111struct ErrorKindVisitor;
112
113impl<'de> Visitor<'de> for ErrorKindVisitor {
114 type Value = ErrorKind;
115
116 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
117 formatter.write_str("enum ErrorKind")
118 }
119
120 fn visit_map<V>(self, mut map: V) -> Result<ErrorKind, V::Error>
121 where
122 V: MapAccess<'de>,
123 {
124 let mut errcode = None;
125 let mut soft_logout = None;
126 let mut retry_after_ms = None;
127 let mut room_version = None;
128 let mut admin_contact = None;
129 let mut status = None;
130 let mut body = None;
131 let mut current_version = None;
132 let mut info_uri = None;
133 let mut can_upgrade = None;
134 #[cfg(feature = "unstable-msc4406")]
135 let mut sender = None;
136 let mut data = JsonObject::new();
137 #[cfg(feature = "unstable-msc4363")]
138 let mut acr_values: Option<JsonValue> = None;
139 #[cfg(feature = "unstable-msc4363")]
140 let mut max_age = None;
141 #[cfg(feature = "unstable-msc4363")]
142 let mut scope: Option<JsonValue> = None;
143
144 macro_rules! set_field {
145 (errcode) => {
146 set_field!(@inner errcode)
147 };
148 ($field:ident) => {
149 match errcode {
150 Some(set_field!(@variant_containing $field)) | None => {
151 set_field!(@inner $field)
152 }
153 Some(_) => {
156 let _ = map.next_value::<de::IgnoredAny>()?;
157 },
158 }
159 };
160 (@variant_containing soft_logout) => { ErrorCode::UnknownToken };
161 (@variant_containing retry_after_ms) => { ErrorCode::LimitExceeded };
162 (@variant_containing room_version) => { ErrorCode::IncompatibleRoomVersion };
163 (@variant_containing admin_contact) => { ErrorCode::ResourceLimitExceeded };
164 (@variant_containing status) => { ErrorCode::BadStatus };
165 (@variant_containing body) => { ErrorCode::BadStatus };
166 (@variant_containing current_version) => { ErrorCode::WrongRoomKeysVersion };
167 (@variant_containing info_uri) => { ErrorCode::UserLimitExceeded };
168 (@variant_containing can_upgrade) => { ErrorCode::UserLimitExceeded };
169 (@variant_containing sender) => { ErrorCode::SenderIgnored };
170 (@variant_containing acr_values) => { ErrorCode::InsufficientUserAuthentication };
171 (@variant_containing max_age) => { ErrorCode::InsufficientUserAuthentication };
172 (@variant_containing scope) => { ErrorCode::InsufficientUserAuthentication };
173 (@inner $field:ident) => {
174 {
175 if $field.is_some() {
176 return Err(de::Error::duplicate_field(stringify!($field)));
177 }
178 $field = Some(map.next_value()?);
179 }
180 };
181 }
182
183 while let Some(key) = map.next_key()? {
184 match key {
185 Field::ErrorCode => set_field!(errcode),
186 Field::SoftLogout => set_field!(soft_logout),
187 Field::RetryAfterMs => set_field!(retry_after_ms),
188 Field::RoomVersion => set_field!(room_version),
189 Field::AdminContact => set_field!(admin_contact),
190 Field::Status => set_field!(status),
191 Field::Body => set_field!(body),
192 Field::CurrentVersion => set_field!(current_version),
193 Field::InfoUri => set_field!(info_uri),
194 Field::CanUpgrade => set_field!(can_upgrade),
195 #[cfg(feature = "unstable-msc4406")]
196 Field::Sender => set_field!(sender),
197 #[cfg(feature = "unstable-msc4363")]
198 Field::AcrValues => set_field!(acr_values),
199 #[cfg(feature = "unstable-msc4363")]
200 Field::MaxAge => set_field!(max_age),
201 #[cfg(feature = "unstable-msc4363")]
202 Field::Scope => set_field!(scope),
203 Field::Other(other) => match data.entry(other.into_owned()) {
204 Entry::Vacant(v) => {
205 v.insert(map.next_value()?);
206 }
207 Entry::Occupied(o) => {
208 return Err(de::Error::custom(format!("duplicate field `{}`", o.key())));
209 }
210 },
211 }
212 }
213
214 let errcode = errcode.ok_or_else(|| de::Error::missing_field("errcode"))?;
215
216 Ok(match errcode {
217 ErrorCode::AppserviceLoginUnsupported => ErrorKind::AppserviceLoginUnsupported,
218 ErrorCode::BadAlias => ErrorKind::BadAlias,
219 ErrorCode::BadJson => ErrorKind::BadJson,
220 ErrorCode::BadState => ErrorKind::BadState,
221 ErrorCode::BadStatus => ErrorKind::BadStatus(BadStatusErrorData {
222 status: status
223 .map(|s| {
224 from_json_value::<u16>(s)
225 .map_err(de::Error::custom)?
226 .try_into()
227 .map_err(de::Error::custom)
228 })
229 .transpose()?,
230 body: body.map(from_json_value).transpose().map_err(de::Error::custom)?,
231 }),
232 ErrorCode::CannotLeaveServerNoticeRoom => ErrorKind::CannotLeaveServerNoticeRoom,
233 ErrorCode::CannotOverwriteMedia => ErrorKind::CannotOverwriteMedia,
234 ErrorCode::CaptchaInvalid => ErrorKind::CaptchaInvalid,
235 ErrorCode::CaptchaNeeded => ErrorKind::CaptchaNeeded,
236 #[cfg(feature = "unstable-msc4388")]
237 ErrorCode::ConcurrentWrite => ErrorKind::ConcurrentWrite,
238 #[cfg(feature = "unstable-msc4306")]
239 ErrorCode::ConflictingUnsubscription => ErrorKind::ConflictingUnsubscription,
240 ErrorCode::ConnectionFailed => ErrorKind::ConnectionFailed,
241 ErrorCode::ConnectionTimeout => ErrorKind::ConnectionTimeout,
242 #[cfg(feature = "unstable-msc4140")]
243 ErrorCode::DelayTooLarge => ErrorKind::DelayTooLarge,
244 ErrorCode::DuplicateAnnotation => ErrorKind::DuplicateAnnotation,
245 ErrorCode::Exclusive => ErrorKind::Exclusive,
246 ErrorCode::Forbidden => ErrorKind::Forbidden,
247 ErrorCode::GuestAccessForbidden => ErrorKind::GuestAccessForbidden,
248 ErrorCode::IncompatibleRoomVersion => {
249 ErrorKind::IncompatibleRoomVersion(IncompatibleRoomVersionErrorData {
250 room_version: from_json_value(
251 room_version.ok_or_else(|| de::Error::missing_field("room_version"))?,
252 )
253 .map_err(de::Error::custom)?,
254 })
255 }
256 #[cfg(feature = "unstable-msc4363")]
257 ErrorCode::InsufficientUserAuthentication => {
258 use crate::{
259 Acr,
260 api::{OAuthClientScope, error::InsufficientUserAuthenticationErrorData},
261 };
262
263 ErrorKind::InsufficientUserAuthentication(Box::new(
264 InsufficientUserAuthenticationErrorData {
265 acr_values: acr_values
266 .clone()
267 .map(from_json_value::<String>)
268 .transpose()
269 .map_err(de::Error::custom)?
270 .map(|value| value.split(" ").map(Acr::parse).collect())
271 .transpose()
272 .map_err(de::Error::custom)?
273 .unwrap_or_default(),
274 max_age: max_age
275 .map(from_json_value::<UInt>)
276 .transpose()
277 .map_err(de::Error::custom)?
278 .map(Into::into)
279 .map(Duration::from_secs),
280 scope: scope
281 .clone()
282 .map(from_json_value::<String>)
283 .transpose()
284 .map_err(de::Error::custom)?
285 .map(|value| value.split(" ").map(OAuthClientScope::try_from).collect())
286 .transpose()
287 .map_err(de::Error::custom)?
288 .unwrap_or_default(),
289 },
290 ))
291 }
292 ErrorCode::InvalidParam => ErrorKind::InvalidParam,
293 ErrorCode::InvalidRoomState => ErrorKind::InvalidRoomState,
294 ErrorCode::InvalidUsername => ErrorKind::InvalidUsername,
295 ErrorCode::InviteBlocked => ErrorKind::InviteBlocked,
296 ErrorCode::KeyTooLarge => ErrorKind::KeyTooLarge,
297 ErrorCode::LimitExceeded => ErrorKind::LimitExceeded(LimitExceededErrorData {
298 retry_after: retry_after_ms
299 .map(from_json_value::<UInt>)
300 .transpose()
301 .map_err(de::Error::custom)?
302 .map(Into::into)
303 .map(Duration::from_millis)
304 .map(RetryAfter::Delay),
305 }),
306 ErrorCode::MissingParam => ErrorKind::MissingParam,
307 ErrorCode::MissingToken => ErrorKind::MissingToken,
308 ErrorCode::NotFound => ErrorKind::NotFound,
309 #[cfg(feature = "unstable-msc4306")]
310 ErrorCode::NotInThread => ErrorKind::NotInThread,
311 ErrorCode::NotJson => ErrorKind::NotJson,
312 ErrorCode::NotYetUploaded => ErrorKind::NotYetUploaded,
313 ErrorCode::ProfileTooLarge => ErrorKind::ProfileTooLarge,
314 ErrorCode::ResourceLimitExceeded => {
315 ErrorKind::ResourceLimitExceeded(ResourceLimitExceededErrorData {
316 admin_contact: from_json_value(
317 admin_contact.ok_or_else(|| de::Error::missing_field("admin_contact"))?,
318 )
319 .map_err(de::Error::custom)?,
320 })
321 }
322 ErrorCode::RoomInUse => ErrorKind::RoomInUse,
323 #[cfg(feature = "unstable-msc4406")]
324 ErrorCode::SenderIgnored => ErrorKind::SenderIgnored(SenderIgnoredErrorData {
325 sender: sender
326 .map(from_json_value::<Option<OwnedUserId>>)
327 .transpose()
328 .map_err(de::Error::custom)?
329 .flatten(),
330 }),
331 ErrorCode::ServerNotTrusted => ErrorKind::ServerNotTrusted,
332 ErrorCode::ThreepidAuthFailed => ErrorKind::ThreepidAuthFailed,
333 ErrorCode::ThreepidDenied => ErrorKind::ThreepidDenied,
334 ErrorCode::ThreepidInUse => ErrorKind::ThreepidInUse,
335 ErrorCode::ThreepidMediumNotSupported => ErrorKind::ThreepidMediumNotSupported,
336 ErrorCode::ThreepidNotFound => ErrorKind::ThreepidNotFound,
337 ErrorCode::TokenIncorrect => ErrorKind::TokenIncorrect,
338 ErrorCode::TooLarge => ErrorKind::TooLarge,
339 ErrorCode::UnableToAuthorizeJoin => ErrorKind::UnableToAuthorizeJoin,
340 ErrorCode::UnableToGrantJoin => ErrorKind::UnableToGrantJoin,
341 #[cfg(feature = "unstable-msc3843")]
342 ErrorCode::Unactionable => ErrorKind::Unactionable,
343 ErrorCode::Unauthorized => ErrorKind::Unauthorized,
344 ErrorCode::Unknown => ErrorKind::Unknown,
345 ErrorCode::UnknownDevice => ErrorKind::UnknownDevice,
346 #[cfg(feature = "unstable-msc4186")]
347 ErrorCode::UnknownPos => ErrorKind::UnknownPos,
348 ErrorCode::UnknownToken => ErrorKind::UnknownToken(UnknownTokenErrorData {
349 soft_logout: soft_logout
350 .map(from_json_value)
351 .transpose()
352 .map_err(de::Error::custom)?
353 .unwrap_or_default(),
354 }),
355 ErrorCode::Unrecognized => ErrorKind::Unrecognized,
356 ErrorCode::UnsupportedRoomVersion => ErrorKind::UnsupportedRoomVersion,
357 ErrorCode::UrlNotSet => ErrorKind::UrlNotSet,
358 ErrorCode::UserDeactivated => ErrorKind::UserDeactivated,
359 ErrorCode::UserInUse => ErrorKind::UserInUse,
360 ErrorCode::UserLimitExceeded => {
361 ErrorKind::UserLimitExceeded(UserLimitExceededErrorData {
362 info_uri: from_json_value(
363 info_uri.ok_or_else(|| de::Error::missing_field("info_uri"))?,
364 )
365 .map_err(de::Error::custom)?,
366 can_upgrade: can_upgrade
367 .map(from_json_value)
368 .transpose()
369 .map_err(de::Error::custom)?
370 .unwrap_or_default(),
371 })
372 }
373 ErrorCode::UserLocked => ErrorKind::UserLocked,
374 ErrorCode::UserSuspended => ErrorKind::UserSuspended,
375 ErrorCode::WeakPassword => ErrorKind::WeakPassword,
376 ErrorCode::WrongRoomKeysVersion => {
377 ErrorKind::WrongRoomKeysVersion(WrongRoomKeysVersionErrorData {
378 current_version: from_json_value(
379 current_version
380 .ok_or_else(|| de::Error::missing_field("current_version"))?,
381 )
382 .map_err(de::Error::custom)?,
383 })
384 }
385 ErrorCode::_Custom(errcode) => {
386 ErrorKind::_Custom(Box::new(CustomErrorKind { errcode: errcode.0.into(), data }))
387 }
388 })
389 }
390}
391
392impl<'de> Deserialize<'de> for ErrorKind {
393 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
394 where
395 D: Deserializer<'de>,
396 {
397 deserializer.deserialize_map(ErrorKindVisitor)
398 }
399}
400
401impl Serialize for ErrorKind {
402 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
403 where
404 S: Serializer,
405 {
406 let mut st = serializer.serialize_map(None)?;
407 st.serialize_entry("errcode", &self.errcode())?;
408 match self {
409 Self::BadStatus(BadStatusErrorData { status, body }) => {
410 if let Some(status) = status {
411 st.serialize_entry("status", &status.as_u16())?;
412 }
413 if let Some(body) = body {
414 st.serialize_entry("body", body)?;
415 }
416 }
417 Self::IncompatibleRoomVersion(IncompatibleRoomVersionErrorData { room_version }) => {
418 st.serialize_entry("room_version", room_version)?;
419 }
420 #[cfg(feature = "unstable-msc4363")]
421 Self::InsufficientUserAuthentication(data) => {
422 let InsufficientUserAuthenticationErrorData { acr_values, max_age, scope } =
423 &**data;
424
425 if !acr_values.is_empty() {
426 st.serialize_entry("org.matrix.msc4363.acr_values", &acr_values.join(" "))?;
427 }
428
429 if let Some(max_age) = max_age {
430 st.serialize_entry(
431 "org.matrix.msc4363.max_age",
432 &UInt::try_from(max_age.as_secs()).map_err(ser::Error::custom)?,
433 )?;
434 }
435
436 if !scope.is_empty() {
437 st.serialize_entry(
438 "org.matrix.msc4363.scope",
439 &scope.iter().map(OAuthClientScope::as_str).collect::<Vec<_>>().join(" "),
442 )?;
443 }
444 }
445 Self::LimitExceeded(LimitExceededErrorData {
446 retry_after: Some(RetryAfter::Delay(duration)),
447 }) => {
448 st.serialize_entry(
449 "retry_after_ms",
450 &UInt::try_from(duration.as_millis()).map_err(ser::Error::custom)?,
451 )?;
452 }
453 Self::ResourceLimitExceeded(ResourceLimitExceededErrorData { admin_contact }) => {
454 st.serialize_entry("admin_contact", admin_contact)?;
455 }
456 Self::UnknownToken(UnknownTokenErrorData { soft_logout: true }) | Self::UserLocked => {
457 st.serialize_entry("soft_logout", &true)?;
458 }
459 Self::UserLimitExceeded(UserLimitExceededErrorData { info_uri, can_upgrade }) => {
460 st.serialize_entry("info_uri", info_uri)?;
461
462 if *can_upgrade {
463 st.serialize_entry("can_upgrade", can_upgrade)?;
464 }
465 }
466 Self::WrongRoomKeysVersion(WrongRoomKeysVersionErrorData { current_version }) => {
467 st.serialize_entry("current_version", current_version)?;
468 }
469 #[cfg(feature = "unstable-msc4406")]
470 Self::SenderIgnored(SenderIgnoredErrorData { sender }) => {
471 if let Some(sender) = sender {
472 st.serialize_entry("sender", sender)?;
473 }
474 }
475 Self::_Custom(kind) => {
476 for (k, v) in &kind.data {
477 st.serialize_entry(k, v)?;
478 }
479 }
480 Self::AppserviceLoginUnsupported
481 | Self::BadAlias
482 | Self::BadJson
483 | Self::BadState
484 | Self::CannotLeaveServerNoticeRoom
485 | Self::CannotOverwriteMedia
486 | Self::CaptchaInvalid
487 | Self::CaptchaNeeded
488 | Self::ConnectionFailed
489 | Self::ConnectionTimeout
490 | Self::DuplicateAnnotation
491 | Self::Exclusive
492 | Self::Forbidden
493 | Self::GuestAccessForbidden
494 | Self::InvalidParam
495 | Self::InvalidRoomState
496 | Self::InvalidUsername
497 | Self::InviteBlocked
498 | Self::KeyTooLarge
499 | Self::LimitExceeded(LimitExceededErrorData {
500 retry_after: None | Some(RetryAfter::DateTime(_)),
501 })
502 | Self::MissingParam
503 | Self::MissingToken
504 | Self::NotFound
505 | Self::NotJson
506 | Self::NotYetUploaded
507 | Self::ProfileTooLarge
508 | Self::RoomInUse
509 | Self::ServerNotTrusted
510 | Self::ThreepidAuthFailed
511 | Self::ThreepidDenied
512 | Self::ThreepidInUse
513 | Self::ThreepidMediumNotSupported
514 | Self::ThreepidNotFound
515 | Self::TokenIncorrect
516 | Self::TooLarge
517 | Self::UnableToAuthorizeJoin
518 | Self::UnableToGrantJoin
519 | Self::Unauthorized
520 | Self::Unknown
521 | Self::UnknownDevice
522 | Self::UnknownToken(UnknownTokenErrorData { soft_logout: false })
523 | Self::Unrecognized
524 | Self::UnsupportedRoomVersion
525 | Self::UrlNotSet
526 | Self::UserDeactivated
527 | Self::UserInUse
528 | Self::UserSuspended
529 | Self::WeakPassword => {}
530 #[cfg(feature = "unstable-msc4306")]
531 Self::ConflictingUnsubscription => {}
532 #[cfg(feature = "unstable-msc4306")]
533 Self::NotInThread => {}
534 #[cfg(feature = "unstable-msc3843")]
535 Self::Unactionable => {}
536 #[cfg(feature = "unstable-msc4186")]
537 Self::UnknownPos => {}
538 #[cfg(feature = "unstable-msc4388")]
539 Self::ConcurrentWrite => {}
540 #[cfg(feature = "unstable-msc4140")]
541 Self::DelayTooLarge => {}
542 }
543 st.end()
544 }
545}
546
547#[cfg(test)]
548mod tests {
549 use ruma_common::room_version_id;
550 use serde_json::{from_value as from_json_value, json};
551
552 use super::{ErrorKind, IncompatibleRoomVersionErrorData};
553
554 #[test]
555 fn deserialize_forbidden() {
556 let deserialized: ErrorKind = from_json_value(json!({ "errcode": "M_FORBIDDEN" })).unwrap();
557 assert_eq!(deserialized, ErrorKind::Forbidden);
558 }
559
560 #[test]
561 fn deserialize_forbidden_with_extra_fields() {
562 let deserialized: ErrorKind = from_json_value(json!({
563 "errcode": "M_FORBIDDEN",
564 "error": "…",
565 }))
566 .unwrap();
567
568 assert_eq!(deserialized, ErrorKind::Forbidden);
569 }
570
571 #[test]
572 fn deserialize_incompatible_room_version() {
573 let deserialized: ErrorKind = from_json_value(json!({
574 "errcode": "M_INCOMPATIBLE_ROOM_VERSION",
575 "room_version": "7",
576 }))
577 .unwrap();
578
579 assert_eq!(
580 deserialized,
581 ErrorKind::IncompatibleRoomVersion(IncompatibleRoomVersionErrorData {
582 room_version: room_version_id!("7")
583 })
584 );
585 }
586
587 #[test]
588 #[cfg(feature = "unstable-msc4363")]
589 fn deserialize_insufficient_user_authentication() {
590 use std::time::Duration;
591
592 use crate::api::{OAuthClientScope, error::InsufficientUserAuthenticationErrorData};
593
594 let deserialized: ErrorKind = from_json_value(json!({
595 "errcode": "M_INSUFFICIENT_USER_AUTHENTICATION",
596 "error": "…",
597 "org.matrix.msc4363.acr_values": "urn:example:foo urn:example:bar",
598 "org.matrix.msc4363.max_age": 300,
599 "org.matrix.msc4363.scope": "urn:matrix:client:api:* urn:example:xyzzy"
600 }))
601 .unwrap();
602
603 assert_eq!(
604 deserialized,
605 ErrorKind::InsufficientUserAuthentication(Box::new(
606 InsufficientUserAuthenticationErrorData {
607 acr_values: vec![
608 "urn:example:foo".parse().unwrap(),
609 "urn:example:bar".parse().unwrap()
610 ],
611 max_age: Some(Duration::from_secs(300)),
612 scope: [
613 OAuthClientScope::ApiFullAccess,
614 "urn:example:xyzzy".try_into().unwrap()
615 ]
616 .into_iter()
617 .collect()
618 }
619 ))
620 );
621 }
622
623 #[test]
624 #[cfg(feature = "unstable-msc4363")]
625 fn serialize_insufficient_user_authentication() {
626 use std::time::Duration;
627
628 use serde_json::to_value as to_json_value;
629
630 use crate::api::{OAuthClientScope, error::InsufficientUserAuthenticationErrorData};
631
632 let serialized = to_json_value(ErrorKind::InsufficientUserAuthentication(Box::new(
633 InsufficientUserAuthenticationErrorData {
634 acr_values: vec![
635 "urn:example:foo".parse().unwrap(),
636 "urn:example:bar".parse().unwrap(),
637 ],
638 max_age: Some(Duration::from_secs(300)),
639 scope: [OAuthClientScope::ApiFullAccess, "urn:example:xyzzy".try_into().unwrap()]
640 .into_iter()
641 .collect(),
642 },
643 )))
644 .unwrap();
645
646 assert_eq!(
647 serialized,
648 json!({
649 "errcode": "M_INSUFFICIENT_USER_AUTHENTICATION",
650 "org.matrix.msc4363.acr_values": "urn:example:foo urn:example:bar",
651 "org.matrix.msc4363.max_age": 300,
652 "org.matrix.msc4363.scope": "urn:example:xyzzy urn:matrix:client:api:*"
653 })
654 );
655 }
656}