Skip to main content

jmap_types/
error.rs

1//! RFC 8620 §3.6 JMAP method-level error type ([`JmapError`],
2//! [`MethodErrorType`]).
3
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7/// The machine-readable `type` of a [`JmapError`].
8///
9/// Known variants are the RFC 8620 request-level error types (§3.6.1,
10/// whose wire form in an RFC 9457 problem-details body is prefixed with
11/// `urn:ietf:params:jmap:error:`), the §3.6.2 method-level error types,
12/// and the method-specific errors of §5.1 to §5.6. Every other wire
13/// string, including extension errors such as `"rateLimited"`, is
14/// [`Self::Other`].
15///
16/// `From<&str>` and `Deserialize` share one mapping: a known wire string
17/// always builds its typed variant, never `Other`.
18#[non_exhaustive]
19#[derive(Debug, Clone, PartialEq, Eq, Hash)]
20pub enum MethodErrorType {
21    /// RFC 8620 §3.6.1 — the request used an unsupported capability.
22    UnknownCapability,
23    /// RFC 8620 §3.6.1 — the content type was not `application/json` or
24    /// the request did not parse as I-JSON.
25    NotJson,
26    /// RFC 8620 §3.6.1 — the request parsed as JSON but not as a Request
27    /// object.
28    NotRequest,
29    /// RFC 8620 §3.6.1 — the request exceeded a server limit; the limit's
30    /// name is [`JmapError::limit_name`].
31    Limit,
32    /// RFC 8620 §3.6.2 — an internal server resource was temporarily
33    /// unavailable.
34    ServerUnavailable,
35    /// RFC 8620 §3.6.2 — an unexpected error occurred.
36    ServerFail,
37    /// RFC 8620 §3.6.2 — some, but not all, expected changes were made.
38    ServerPartialFail,
39    /// RFC 8620 §3.6.2 — the server does not recognise this method name.
40    UnknownMethod,
41    /// RFC 8620 §3.6.2 — an argument is of the wrong type or invalid.
42    InvalidArguments,
43    /// RFC 8620 §3.6.2 — a result reference failed to resolve.
44    InvalidResultReference,
45    /// RFC 8620 §3.6.2 — the method or arguments are forbidden.
46    Forbidden,
47    /// RFC 8620 §3.6.2 — the `accountId` does not correspond to a valid
48    /// account.
49    AccountNotFound,
50    /// RFC 8620 §3.6.2 — the account does not support this method.
51    AccountNotSupportedByMethod,
52    /// RFC 8620 §3.6.2 — the account is read-only.
53    AccountReadOnly,
54    /// RFC 8620 §5.1 and §5.3 — too many ids or objects in one call.
55    RequestTooLarge,
56    /// RFC 8620 §5.2 and §5.6 — the server cannot calculate the changes
57    /// from the given state.
58    CannotCalculateChanges,
59    /// RFC 8620 §5.3 and §5.4 — `ifInState` did not match the current
60    /// state.
61    StateMismatch,
62    /// RFC 8620 §5.4 — the `fromAccountId` does not correspond to a valid
63    /// account.
64    FromAccountNotFound,
65    /// RFC 8620 §5.4 — the `fromAccountId` account does not support this
66    /// method.
67    FromAccountNotSupportedByMethod,
68    /// RFC 8620 §5.5 — the anchor was not found in the results.
69    AnchorNotFound,
70    /// RFC 8620 §5.5 — the sort is syntactically valid but unsupported.
71    UnsupportedSort,
72    /// RFC 8620 §5.5 — the filter is syntactically valid but unsupported.
73    UnsupportedFilter,
74    /// RFC 8620 §5.6 — there are more changes than `maxChanges`.
75    TooManyChanges,
76    /// Any other error type, such as an extension's.
77    Other(String),
78}
79
80crate::impl_string_enum!(
81    MethodErrorType,
82    "a JMAP method error type string",
83    "unknownCapability" => UnknownCapability,
84    "notJSON" => NotJson,
85    "notRequest" => NotRequest,
86    "limit" => Limit,
87    "serverUnavailable" => ServerUnavailable,
88    "serverFail" => ServerFail,
89    "serverPartialFail" => ServerPartialFail,
90    "unknownMethod" => UnknownMethod,
91    "invalidArguments" => InvalidArguments,
92    "invalidResultReference" => InvalidResultReference,
93    "forbidden" => Forbidden,
94    "accountNotFound" => AccountNotFound,
95    "accountNotSupportedByMethod" => AccountNotSupportedByMethod,
96    "accountReadOnly" => AccountReadOnly,
97    "requestTooLarge" => RequestTooLarge,
98    "cannotCalculateChanges" => CannotCalculateChanges,
99    "stateMismatch" => StateMismatch,
100    "fromAccountNotFound" => FromAccountNotFound,
101    "fromAccountNotSupportedByMethod" => FromAccountNotSupportedByMethod,
102    "anchorNotFound" => AnchorNotFound,
103    "unsupportedSort" => UnsupportedSort,
104    "unsupportedFilter" => UnsupportedFilter,
105    "tooManyChanges" => TooManyChanges,
106);
107
108/// JMAP method-level error, serializable for inclusion in `methodResponses`.
109///
110/// See RFC 8620 §3.6.2 for the standard error types.
111/// The JSON key is `"type"` (not `"error_type"`) per RFC 8620.
112#[non_exhaustive]
113#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)]
114#[error("{error_type}")]
115pub struct JmapError {
116    /// Error type per RFC 8620 §3.6.
117    #[serde(rename = "type")]
118    pub error_type: MethodErrorType,
119    /// Human-readable description. Omitted from JSON when `None`.
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub description: Option<String>,
122    /// Maximum `maxChanges` value the server will accept. Only set for `"tooManyChanges"` (RFC 8620 §9.6.1 MUST).
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub limit: Option<u64>,
125    /// Name of the exceeded limit for a request-level `limit` error
126    /// (RFC 8620 §3.6.1: "the "limit" property MUST contain the name of
127    /// the limit being applied"), e.g. `"maxCallsInRequest"`.
128    ///
129    /// Request-level errors are sent as an RFC 9457 problem-details body,
130    /// where `jmap-server` writes this as the `"limit"` property. It never
131    /// appears in a `methodResponses` error, so it is not serialized here
132    /// (the `limit` key there is the `tooManyChanges` count).
133    #[serde(skip)]
134    pub limit_name: Option<String>,
135    /// Other properties of the error object (RFC 8620 §3.6.2: "Other
136    /// properties may be present"), such as draft-ietf-jmap-conditional-02
137    /// §3.3 `failed` and the §4.2 `atomicFailure` maps. Kept on decode
138    /// and written flat beside `type`.
139    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
140    pub extra: serde_json::Map<String, serde_json::Value>,
141}
142
143impl JmapError {
144    /// RFC 8620 §3.6.2 — "invalidArguments"
145    pub fn invalid_arguments(desc: impl Into<String>) -> Self {
146        Self {
147            error_type: MethodErrorType::InvalidArguments,
148            description: Some(desc.into()),
149            limit: None,
150            limit_name: None,
151            extra: serde_json::Map::new(),
152        }
153    }
154
155    /// RFC 8620 §3.6.2 — "forbidden"
156    pub fn forbidden() -> Self {
157        Self {
158            error_type: MethodErrorType::Forbidden,
159            description: None,
160            limit: None,
161            limit_name: None,
162            extra: serde_json::Map::new(),
163        }
164    }
165
166    /// RFC 8620 §5.1 — "accountNotFound"
167    pub fn account_not_found() -> Self {
168        Self {
169            error_type: MethodErrorType::AccountNotFound,
170            description: None,
171            limit: None,
172            limit_name: None,
173            extra: serde_json::Map::new(),
174        }
175    }
176
177    /// RFC 8620 §5.1 — "accountNotSupportedByMethod"
178    pub fn account_not_supported_by_method() -> Self {
179        Self {
180            error_type: MethodErrorType::AccountNotSupportedByMethod,
181            description: None,
182            limit: None,
183            limit_name: None,
184            extra: serde_json::Map::new(),
185        }
186    }
187
188    /// RFC 8620 §5.1 — "accountReadOnly"
189    pub fn account_read_only() -> Self {
190        Self {
191            error_type: MethodErrorType::AccountReadOnly,
192            description: None,
193            limit: None,
194            limit_name: None,
195            extra: serde_json::Map::new(),
196        }
197    }
198
199    /// RFC 8620 §3.6.2 — "serverUnavailable"
200    pub fn server_unavailable() -> Self {
201        Self {
202            error_type: MethodErrorType::ServerUnavailable,
203            description: None,
204            limit: None,
205            limit_name: None,
206            extra: serde_json::Map::new(),
207        }
208    }
209
210    /// RFC 8620 §3.6.2 — "serverFail"
211    pub fn server_fail(desc: impl Into<String>) -> Self {
212        Self {
213            error_type: MethodErrorType::ServerFail,
214            description: Some(desc.into()),
215            limit: None,
216            limit_name: None,
217            extra: serde_json::Map::new(),
218        }
219    }
220
221    /// RFC 8620 §3.6.2 — "serverPartialFail"
222    pub fn server_partial_fail() -> Self {
223        Self {
224            error_type: MethodErrorType::ServerPartialFail,
225            description: None,
226            limit: None,
227            limit_name: None,
228            extra: serde_json::Map::new(),
229        }
230    }
231
232    /// RFC 8620 §3.6.2 — "unknownMethod"
233    pub fn unknown_method() -> Self {
234        Self {
235            error_type: MethodErrorType::UnknownMethod,
236            description: None,
237            limit: None,
238            limit_name: None,
239            extra: serde_json::Map::new(),
240        }
241    }
242
243    /// RFC 8620 §3.6.2 — "invalidResultReference"
244    pub fn invalid_result_reference() -> Self {
245        Self {
246            error_type: MethodErrorType::InvalidResultReference,
247            description: None,
248            limit: None,
249            limit_name: None,
250            extra: serde_json::Map::new(),
251        }
252    }
253
254    /// RFC 8620 §5.2 and §5.6 — "cannotCalculateChanges"
255    pub fn cannot_calculate_changes() -> Self {
256        Self {
257            error_type: MethodErrorType::CannotCalculateChanges,
258            description: None,
259            limit: None,
260            limit_name: None,
261            extra: serde_json::Map::new(),
262        }
263    }
264
265    /// RFC 8620 §5.3 — "stateMismatch"
266    pub fn state_mismatch() -> Self {
267        Self {
268            error_type: MethodErrorType::StateMismatch,
269            description: None,
270            limit: None,
271            limit_name: None,
272            extra: serde_json::Map::new(),
273        }
274    }
275
276    /// "tooLarge" — a method-level error of `Principal/getAvailability`
277    /// (draft-ietf-jmap-calendars §2.2); RFC 8620 §5.3 defines it only as
278    /// a SetError.
279    pub fn too_large() -> Self {
280        Self {
281            error_type: MethodErrorType::from("tooLarge"),
282            description: None,
283            limit: None,
284            limit_name: None,
285            extra: serde_json::Map::new(),
286        }
287    }
288
289    /// RFC 8620 §5.1 and §5.3 — "requestTooLarge"
290    pub fn request_too_large() -> Self {
291        Self {
292            error_type: MethodErrorType::RequestTooLarge,
293            description: None,
294            limit: None,
295            limit_name: None,
296            extra: serde_json::Map::new(),
297        }
298    }
299
300    /// "rateLimit" — a method-level error of `Principal/getAvailability`
301    /// (draft-ietf-jmap-calendars §2.2); RFC 8620 §5.3 defines it only as
302    /// a SetError.
303    pub fn rate_limit() -> Self {
304        Self {
305            error_type: MethodErrorType::from("rateLimit"),
306            description: None,
307            limit: None,
308            limit_name: None,
309            extra: serde_json::Map::new(),
310        }
311    }
312
313    /// RFC 8620 §5.5 — "unsupportedFilter"
314    pub fn unsupported_filter() -> Self {
315        Self {
316            error_type: MethodErrorType::UnsupportedFilter,
317            description: None,
318            limit: None,
319            limit_name: None,
320            extra: serde_json::Map::new(),
321        }
322    }
323
324    /// RFC 8620 §5.5 — "anchorNotFound"
325    pub fn anchor_not_found() -> Self {
326        Self {
327            error_type: MethodErrorType::AnchorNotFound,
328            description: None,
329            limit: None,
330            limit_name: None,
331            extra: serde_json::Map::new(),
332        }
333    }
334
335    /// RFC 8620 §5.4 — "fromAccountNotFound"
336    pub fn from_account_not_found() -> Self {
337        Self {
338            error_type: MethodErrorType::FromAccountNotFound,
339            description: None,
340            limit: None,
341            limit_name: None,
342            extra: serde_json::Map::new(),
343        }
344    }
345
346    /// RFC 8620 §5.4 — "fromAccountNotSupportedByMethod"
347    pub fn from_account_not_supported_by_method() -> Self {
348        Self {
349            error_type: MethodErrorType::FromAccountNotSupportedByMethod,
350            description: None,
351            limit: None,
352            limit_name: None,
353            extra: serde_json::Map::new(),
354        }
355    }
356
357    /// RFC 8620 §5.5 — "unsupportedSort"
358    pub fn unsupported_sort() -> Self {
359        Self {
360            error_type: MethodErrorType::UnsupportedSort,
361            description: None,
362            limit: None,
363            limit_name: None,
364            extra: serde_json::Map::new(),
365        }
366    }
367
368    /// Returns a `tooManyChanges` error with the server's limit included.
369    ///
370    /// Per RFC 8620 §9.6.1, the `limit` field MUST be present so the client
371    /// knows the maximum `maxChanges` value to use on retry.
372    pub fn too_many_changes_with_limit(limit: u64) -> Self {
373        Self {
374            error_type: MethodErrorType::TooManyChanges,
375            description: None,
376            limit: Some(limit),
377            limit_name: None,
378            extra: serde_json::Map::new(),
379        }
380    }
381
382    /// RFC 8620 §3.6.1 — "notJSON" (request-level error)
383    ///
384    /// The request body was not valid JSON or did not have `application/json` content type.
385    pub fn not_json() -> Self {
386        Self {
387            error_type: MethodErrorType::NotJson,
388            description: None,
389            limit: None,
390            limit_name: None,
391            extra: serde_json::Map::new(),
392        }
393    }
394
395    /// RFC 8620 §3.6.1 — "notRequest" (request-level error)
396    ///
397    /// The request parsed as JSON but did not match the JMAP Request object shape.
398    pub fn not_request() -> Self {
399        Self {
400            error_type: MethodErrorType::NotRequest,
401            description: None,
402            limit: None,
403            limit_name: None,
404            extra: serde_json::Map::new(),
405        }
406    }
407
408    /// RFC 8620 §3.6.1 — "limit" (request-level error)
409    ///
410    /// The request was rejected because it would exceed a capability limit such as
411    /// `maxCallsInRequest` or `maxSizeRequest`.
412    ///
413    /// `limit_name` is the name of the exceeded limit (e.g. `"maxCallsInRequest"`),
414    /// stored in [`limit_name`][JmapError::limit_name]. The HTTP layer
415    /// (`jmap-server::RequestError`) writes it as the RFC-required `"limit"`
416    /// property of the RFC 9457 problem-details body.
417    pub fn limit(limit_name: impl Into<String>) -> Self {
418        Self {
419            error_type: MethodErrorType::Limit,
420            description: None,
421            limit: None,
422            limit_name: Some(limit_name.into()),
423            extra: serde_json::Map::new(),
424        }
425    }
426
427    /// "unknownCapability" with the failing URI surfaced to the client.
428    ///
429    /// The URI is stored in [`description`][JmapError::description].  The HTTP layer
430    /// (`jmap-server::RequestError`) reads `description` to populate the `"detail"` field
431    /// in the RFC 9457 problem-details response body — the same mechanism used by
432    /// [`limit()`][Self::limit] for its limit-name payload.
433    ///
434    /// **Invariant**: always construct unknownCapability errors that carry a URI with this
435    /// function, never by setting `description` manually.  A missing or incorrect description
436    /// means the client never learns which capability it requested that the server does not
437    /// support.
438    pub fn unknown_capability_with_detail(uri: impl Into<String>) -> Self {
439        Self {
440            error_type: MethodErrorType::UnknownCapability,
441            description: Some(uri.into()),
442            limit: None,
443            limit_name: None,
444            extra: serde_json::Map::new(),
445        }
446    }
447
448    /// Create a `JmapError` with an extension error type such as
449    /// `"rateLimited"`.
450    ///
451    /// A string naming a known type builds that variant
452    /// (`JmapError::custom("forbidden")` equals [`JmapError::forbidden`]).
453    pub fn custom(error_type: impl Into<MethodErrorType>) -> Self {
454        Self {
455            error_type: error_type.into(),
456            description: None,
457            limit: None,
458            limit_name: None,
459            extra: serde_json::Map::new(),
460        }
461    }
462}
463
464/// Name the top-level JSON type of `v` (`null`, `boolean`, `number`,
465/// `string`, `array` or `object`) for an error description.
466///
467/// Malformed-argument errors interpolate this tag instead of the value
468/// itself. `Value`'s `Display` re-serialises arbitrary client-supplied JSON,
469/// so echoing it would let a request amplify its own error response and
470/// copy attacker-controlled text into the `description` that RFC 8620
471/// §3.6.1 reserves for "unstructured English text suitable for displaying
472/// to a developer" (and into any log that buffers responses).
473#[must_use]
474pub fn json_type_name(v: &serde_json::Value) -> &'static str {
475    match v {
476        serde_json::Value::Null => "null",
477        serde_json::Value::Bool(_) => "boolean",
478        serde_json::Value::Number(_) => "number",
479        serde_json::Value::String(_) => "string",
480        serde_json::Value::Array(_) => "array",
481        serde_json::Value::Object(_) => "object",
482    }
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488
489    // Independent oracle: RFC 8620 §3.6.2 and §5.x specify these exact type strings.
490
491    #[test]
492    fn invalid_arguments_serializes_type_and_description() {
493        let e = JmapError::invalid_arguments("ids field is required");
494        let json = serde_json::to_string(&e).unwrap();
495        assert!(
496            json.contains("\"type\""),
497            "must use 'type' key per RFC 8620"
498        );
499        assert!(json.contains("\"invalidArguments\""));
500        assert!(json.contains("\"description\""));
501        assert!(json.contains("ids field is required"));
502    }
503
504    #[test]
505    fn forbidden_omits_description() {
506        let e = JmapError::forbidden();
507        let json = serde_json::to_string(&e).unwrap();
508        assert!(json.contains("\"forbidden\""));
509        assert!(
510            !json.contains("\"description\""),
511            "None description must be omitted"
512        );
513    }
514
515    #[test]
516    fn account_not_found_type_string() {
517        let e = JmapError::account_not_found();
518        let json = serde_json::to_string(&e).unwrap();
519        assert!(json.contains("\"accountNotFound\""));
520        assert!(!json.contains("\"description\""));
521    }
522
523    #[test]
524    fn account_not_supported_by_method_type_string() {
525        let e = JmapError::account_not_supported_by_method();
526        let json = serde_json::to_string(&e).unwrap();
527        assert!(json.contains("\"accountNotSupportedByMethod\""));
528    }
529
530    #[test]
531    fn account_read_only_type_string() {
532        let e = JmapError::account_read_only();
533        let json = serde_json::to_string(&e).unwrap();
534        assert!(json.contains("\"accountReadOnly\""));
535    }
536
537    #[test]
538    fn server_unavailable_type_string() {
539        let e = JmapError::server_unavailable();
540        let json = serde_json::to_string(&e).unwrap();
541        assert!(json.contains("\"serverUnavailable\""));
542    }
543
544    #[test]
545    fn server_fail_includes_description() {
546        let e = JmapError::server_fail("internal error");
547        let json = serde_json::to_string(&e).unwrap();
548        assert!(json.contains("\"serverFail\""));
549        assert!(json.contains("internal error"));
550    }
551
552    #[test]
553    fn server_partial_fail_type_string() {
554        let e = JmapError::server_partial_fail();
555        let json = serde_json::to_string(&e).unwrap();
556        assert!(json.contains("\"serverPartialFail\""));
557    }
558
559    #[test]
560    fn unknown_method_type_string() {
561        let e = JmapError::unknown_method();
562        let json = serde_json::to_string(&e).unwrap();
563        assert!(json.contains("\"unknownMethod\""));
564    }
565
566    #[test]
567    fn invalid_result_reference_type_string() {
568        let e = JmapError::invalid_result_reference();
569        let json = serde_json::to_string(&e).unwrap();
570        assert!(json.contains("\"invalidResultReference\""));
571    }
572
573    #[test]
574    fn cannot_calculate_changes_type_string() {
575        let e = JmapError::cannot_calculate_changes();
576        let json = serde_json::to_string(&e).unwrap();
577        assert!(json.contains("\"cannotCalculateChanges\""));
578    }
579
580    #[test]
581    fn state_mismatch_type_string() {
582        let e = JmapError::state_mismatch();
583        let json = serde_json::to_string(&e).unwrap();
584        assert!(json.contains("\"stateMismatch\""));
585    }
586
587    #[test]
588    fn too_large_type_string() {
589        let e = JmapError::too_large();
590        let json = serde_json::to_string(&e).unwrap();
591        assert!(json.contains("\"tooLarge\""));
592    }
593
594    #[test]
595    fn request_too_large_type_string() {
596        let e = JmapError::request_too_large();
597        let json = serde_json::to_string(&e).unwrap();
598        assert!(json.contains("\"requestTooLarge\""));
599        assert!(!json.contains("\"description\""));
600    }
601
602    #[test]
603    fn rate_limit_type_string() {
604        let e = JmapError::rate_limit();
605        let json = serde_json::to_string(&e).unwrap();
606        assert!(json.contains("\"rateLimit\""));
607    }
608
609    #[test]
610    fn unsupported_filter_type_string() {
611        let e = JmapError::unsupported_filter();
612        let json = serde_json::to_string(&e).unwrap();
613        assert!(json.contains("\"unsupportedFilter\""));
614    }
615
616    #[test]
617    fn anchor_not_found_type_string() {
618        let e = JmapError::anchor_not_found();
619        let json = serde_json::to_string(&e).unwrap();
620        assert!(json.contains("\"anchorNotFound\""));
621    }
622
623    #[test]
624    fn from_account_not_found_type_string() {
625        let e = JmapError::from_account_not_found();
626        let json = serde_json::to_string(&e).unwrap();
627        assert!(json.contains("\"fromAccountNotFound\""));
628        assert!(!json.contains("\"description\""));
629    }
630
631    #[test]
632    fn from_account_not_supported_by_method_type_string() {
633        let e = JmapError::from_account_not_supported_by_method();
634        let json = serde_json::to_string(&e).unwrap();
635        assert!(json.contains("\"fromAccountNotSupportedByMethod\""));
636        assert!(!json.contains("\"description\""));
637    }
638
639    #[test]
640    fn unsupported_sort_type_string() {
641        let e = JmapError::unsupported_sort();
642        let json = serde_json::to_string(&e).unwrap();
643        assert!(json.contains("\"unsupportedSort\""));
644        assert!(!json.contains("\"description\""));
645    }
646
647    #[test]
648    fn too_many_changes_with_limit_serializes_limit_field() {
649        let err = JmapError::too_many_changes_with_limit(100);
650        let v = serde_json::to_value(&err).unwrap();
651        assert_eq!(v["type"], "tooManyChanges");
652        assert_eq!(v["limit"], 100u64);
653        assert!(v.get("description").is_none());
654    }
655
656    #[test]
657    fn not_json_type_string() {
658        let e = JmapError::not_json();
659        let json = serde_json::to_string(&e).unwrap();
660        assert!(json.contains("\"notJSON\""));
661        assert!(!json.contains("\"description\""));
662    }
663
664    #[test]
665    fn not_request_type_string() {
666        let e = JmapError::not_request();
667        let json = serde_json::to_string(&e).unwrap();
668        assert!(json.contains("\"notRequest\""));
669        assert!(!json.contains("\"description\""));
670    }
671
672    #[test]
673    fn limit_carries_limit_name_in_its_own_field() {
674        // Oracle: RFC 8620 §3.6.1 — "the "limit" property MUST contain the
675        // name of the limit being applied". The name has its own field, not
676        // the human-readable description.
677        let e = JmapError::limit("maxCallsInRequest");
678        assert_eq!(e.error_type, MethodErrorType::Limit);
679        assert_eq!(e.limit_name.as_deref(), Some("maxCallsInRequest"));
680        assert_eq!(e.description, None);
681        // The name only travels in the problem-details body; the
682        // methodResponses form is just the type.
683        assert_eq!(
684            serde_json::to_value(&e).unwrap(),
685            serde_json::json!({"type": "limit"})
686        );
687    }
688
689    // Oracle: RFC 8620 §3.6.1 — unknownCapability with detail includes the URI.
690    #[test]
691    fn unknown_capability_with_detail_includes_uri() {
692        let e = JmapError::unknown_capability_with_detail("urn:example:unknown");
693        assert_eq!(e.error_type, MethodErrorType::UnknownCapability);
694        assert_eq!(e.description.as_deref(), Some("urn:example:unknown"));
695    }
696
697    #[test]
698    fn custom_error_type_round_trips() {
699        let e = JmapError::custom("urn:example:customError");
700        assert_eq!(
701            e.error_type,
702            MethodErrorType::Other("urn:example:customError".to_owned())
703        );
704        let json = serde_json::to_string(&e).unwrap();
705        assert!(json.contains("\"urn:example:customError\""));
706        let restored: JmapError = serde_json::from_str(&json).unwrap();
707        assert_eq!(restored, e);
708    }
709
710    #[test]
711    fn round_trip_deserialize() {
712        // Verify the "type" rename survives a JSON round-trip.
713        let original = JmapError::invalid_arguments("test");
714        let json = serde_json::to_string(&original).unwrap();
715        let restored: JmapError = serde_json::from_str(&json).unwrap();
716        assert_eq!(restored.error_type, MethodErrorType::InvalidArguments);
717        assert_eq!(restored.description.as_deref(), Some("test"));
718    }
719
720    // Oracle: the error type strings of RFC 8620 §3.6.1, §3.6.2 and
721    // §5.1-§5.6, hand-copied. Each must serialize to that string and decode
722    // back to its typed variant, never `Other`.
723    #[test]
724    fn method_error_type_all_known_variants_round_trip() {
725        let cases: &[(MethodErrorType, &str)] = &[
726            (MethodErrorType::UnknownCapability, "unknownCapability"),
727            (MethodErrorType::NotJson, "notJSON"),
728            (MethodErrorType::NotRequest, "notRequest"),
729            (MethodErrorType::Limit, "limit"),
730            (MethodErrorType::ServerUnavailable, "serverUnavailable"),
731            (MethodErrorType::ServerFail, "serverFail"),
732            (MethodErrorType::ServerPartialFail, "serverPartialFail"),
733            (MethodErrorType::UnknownMethod, "unknownMethod"),
734            (MethodErrorType::InvalidArguments, "invalidArguments"),
735            (
736                MethodErrorType::InvalidResultReference,
737                "invalidResultReference",
738            ),
739            (MethodErrorType::Forbidden, "forbidden"),
740            (MethodErrorType::AccountNotFound, "accountNotFound"),
741            (
742                MethodErrorType::AccountNotSupportedByMethod,
743                "accountNotSupportedByMethod",
744            ),
745            (MethodErrorType::AccountReadOnly, "accountReadOnly"),
746            (MethodErrorType::RequestTooLarge, "requestTooLarge"),
747            (
748                MethodErrorType::CannotCalculateChanges,
749                "cannotCalculateChanges",
750            ),
751            (MethodErrorType::StateMismatch, "stateMismatch"),
752            (MethodErrorType::FromAccountNotFound, "fromAccountNotFound"),
753            (
754                MethodErrorType::FromAccountNotSupportedByMethod,
755                "fromAccountNotSupportedByMethod",
756            ),
757            (MethodErrorType::AnchorNotFound, "anchorNotFound"),
758            (MethodErrorType::UnsupportedSort, "unsupportedSort"),
759            (MethodErrorType::UnsupportedFilter, "unsupportedFilter"),
760            (MethodErrorType::TooManyChanges, "tooManyChanges"),
761        ];
762        for (variant, wire) in cases {
763            assert_eq!(
764                serde_json::to_value(variant).unwrap(),
765                serde_json::Value::String((*wire).to_owned())
766            );
767            let decoded: MethodErrorType =
768                serde_json::from_value(serde_json::Value::String((*wire).to_owned())).unwrap();
769            assert_eq!(&decoded, variant, "{wire} must decode to its variant");
770            assert_eq!(&MethodErrorType::from(*wire), variant);
771        }
772        // An extension type stays Other and round-trips verbatim.
773        let decoded: MethodErrorType = serde_json::from_str(r#""rateLimited""#).unwrap();
774        assert_eq!(decoded, MethodErrorType::Other("rateLimited".to_owned()));
775        assert_eq!(serde_json::to_string(&decoded).unwrap(), r#""rateLimited""#);
776    }
777
778    // Oracle: RFC 8620 §3.4.1 fixture — methodResponses[3] is ["error", {"type":"unknownMethod"}, "c3"]
779    #[test]
780    fn fixture_response_contains_unknown_method_error() {
781        let raw = include_str!("../tests/fixtures/rfc8620-response.json");
782        let v: serde_json::Value = serde_json::from_str(raw).expect("parse fixture");
783        let inv = &v["methodResponses"][3];
784        assert_eq!(inv[0], "error");
785        assert_eq!(inv[1]["type"], "unknownMethod");
786        assert_eq!(inv[2], "c3");
787    }
788
789    /// RFC 8620 §3.6.2 "Other properties may be present": a decoded error
790    /// keeps them in `extra` and writes them back.
791    #[test]
792    fn unknown_properties_round_trip() {
793        let wire = serde_json::json!({
794            "type": "urn:example:custom",
795            "description": "d",
796            "detail": {"n": 1},
797            "ids": ["a"]
798        });
799        let e: JmapError = serde_json::from_value(wire.clone()).unwrap();
800        assert_eq!(e.description.as_deref(), Some("d"));
801        assert_eq!(e.extra.len(), 2);
802        assert_eq!(e.extra["detail"], serde_json::json!({"n": 1}));
803        assert_eq!(serde_json::to_value(&e).unwrap(), wire);
804        // An error without extra properties writes none.
805        assert_eq!(
806            serde_json::to_value(JmapError::state_mismatch()).unwrap(),
807            serde_json::json!({"type": "stateMismatch"})
808        );
809    }
810
811    /// `JmapError` sits in every handler `Result`, so its size is watched:
812    /// `extra` is one `Map` rather than typed fields. A runtime check, not
813    /// a static assert: `serde_json/preserve_order` changes `Map`'s size.
814    #[test]
815    fn size_stays_small() {
816        // 88 bytes before `extra` was added (64-bit, measured 2026-11-15);
817        // `extra` may add one `Map` and nothing more.
818        let size = std::mem::size_of::<JmapError>();
819        let map = std::mem::size_of::<serde_json::Map<String, serde_json::Value>>();
820        assert!(size <= 88 + map, "JmapError is {size} bytes");
821    }
822}