Skip to main content

jmap_types/
problem.rs

1//! RFC 9457 problem details, the error body of every JMAP HTTP resource.
2//!
3//! RFC 8620 §3.6.1 sends request-level errors as problem details (citing
4//! RFC 7807, which RFC 9457 obsoletes). draft-atwood-jmap-updates-00 §7.2
5//! asks that every JMAP HTTP resource do the same on a 4xx or 5xx: the
6//! Session resource, the API, upload, download, the event source, the
7//! WebSocket opening handshake, and the resources extensions add. Types
8//! that JMAP registers carry the `urn:ietf:params:jmap:error:` prefix
9//! (RFC 8620 §9.5); a problem with no specific type uses `about:blank`
10//! (RFC 9457 §4.2.1).
11//!
12//! `title` and `detail` are display text: a server MAY localize them
13//! from Accept-Language and then labels the response with
14//! Content-Language. Clients act on [`ProblemDetails::problem_type`] and
15//! the HTTP status, never on `title` or `detail`.
16
17use serde::{Deserialize, Serialize};
18use serde_json::{Map, Value};
19
20use crate::{JmapError, MethodErrorType};
21
22/// The media type of a problem details body (RFC 9457 §3).
23pub const PROBLEM_JSON: &str = "application/problem+json";
24
25/// The prefix of JMAP problem type URIs (RFC 8620 §9.5: the JMAP Error
26/// Codes registry).
27pub const JMAP_ERROR_URN_PREFIX: &str = "urn:ietf:params:jmap:error:";
28
29/// The type of a problem with no more specific type (RFC 9457 §4.2.1):
30/// its `title` should be the HTTP status phrase.
31pub const ABOUT_BLANK: &str = "about:blank";
32
33/// An RFC 9457 problem details object, with the `limit` member RFC 8620
34/// §3.6.1 adds for `limit` errors.
35///
36/// Build one with [`ProblemDetails::new`], [`ProblemDetails::for_status`]
37/// or [`ProblemDetails::for_jmap_error`] and the `with_*` setters, or
38/// deserialize it from a response body.
39///
40/// ```rust
41/// use jmap_types::problem::ProblemDetails;
42///
43/// let p = ProblemDetails::for_jmap_error(&jmap_types::JmapError::not_json(), 400)
44///     .with_title("Not JSON");
45/// assert_eq!(p.problem_type, "urn:ietf:params:jmap:error:notJSON");
46/// assert_eq!(p.jmap_error_type().unwrap().to_string(), "notJSON");
47/// ```
48#[non_exhaustive]
49#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
50pub struct ProblemDetails {
51    /// `type`: a URI naming the problem type (RFC 9457 §3.1.1); absent
52    /// on the wire means [`ABOUT_BLANK`].
53    #[serde(rename = "type", default = "about_blank")]
54    pub problem_type: String,
55    /// `status`: the HTTP status code (RFC 9457 §3.1.2).
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub status: Option<u16>,
58    /// `title`: a short summary of the problem type (RFC 9457 §3.1.3);
59    /// display text, MAY be localized.
60    #[serde(default, skip_serializing_if = "Option::is_none")]
61    pub title: Option<String>,
62    /// `detail`: an explanation of this occurrence (RFC 9457 §3.1.4);
63    /// display text, MAY be localized.
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub detail: Option<String>,
66    /// `instance`: a URI reference for this occurrence (RFC 9457 §3.1.5).
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub instance: Option<String>,
69    /// `limit`: the name of the exceeded limit of a JMAP `limit` error
70    /// (RFC 8620 §3.6.1, MUST for that type).
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub limit: Option<String>,
73    /// Extension members (RFC 9457 §3.2), e.g. RFC 8887's `requestId`.
74    #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
75    pub extra: Map<String, Value>,
76}
77
78fn about_blank() -> String {
79    ABOUT_BLANK.to_owned()
80}
81
82impl ProblemDetails {
83    /// A problem of type `problem_type` with HTTP status `status`.
84    pub fn new(problem_type: impl Into<String>, status: u16) -> Self {
85        Self {
86            problem_type: problem_type.into(),
87            status: Some(status),
88            title: None,
89            detail: None,
90            instance: None,
91            limit: None,
92            extra: Map::new(),
93        }
94    }
95
96    /// An [`ABOUT_BLANK`] problem for an HTTP status with no more specific
97    /// type, e.g. 401 or 404 (RFC 9457 §4.2.1). Set the title to the
98    /// status phrase with [`Self::with_title`].
99    pub fn for_status(status: u16) -> Self {
100        Self::new(ABOUT_BLANK, status)
101    }
102
103    /// The problem for a JMAP request-level error (RFC 8620 §3.6.1): type
104    /// `urn:ietf:params:jmap:error:<type>`, `detail` from the error's
105    /// description, and `limit` from [`JmapError::limit_name`] for a
106    /// `limit` error (`"unknown"` if unset, since RFC 8620 requires it).
107    pub fn for_jmap_error(err: &JmapError, status: u16) -> Self {
108        let mut p = Self::new(format!("{JMAP_ERROR_URN_PREFIX}{}", err.error_type), status);
109        p.detail = err.description.clone();
110        if err.error_type == MethodErrorType::Limit {
111            p.limit = Some(
112                err.limit_name
113                    .clone()
114                    .unwrap_or_else(|| "unknown".to_owned()),
115            );
116        }
117        p
118    }
119
120    /// Set [`title`](Self::title).
121    #[must_use]
122    pub fn with_title(mut self, title: impl Into<String>) -> Self {
123        self.title = Some(title.into());
124        self
125    }
126
127    /// Set [`detail`](Self::detail).
128    #[must_use]
129    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
130        self.detail = Some(detail.into());
131        self
132    }
133
134    /// Set [`instance`](Self::instance).
135    #[must_use]
136    pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
137        self.instance = Some(instance.into());
138        self
139    }
140
141    /// The JMAP error type when [`problem_type`](Self::problem_type) is a
142    /// `urn:ietf:params:jmap:error:` URI, compared exactly
143    /// (draft-atwood-jmap-updates-00 §7.1); `None` otherwise.
144    pub fn jmap_error_type(&self) -> Option<MethodErrorType> {
145        self.problem_type
146            .strip_prefix(JMAP_ERROR_URN_PREFIX)
147            .map(MethodErrorType::from)
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use serde_json::json;
155
156    /// RFC 8620 §3.6.1.1 example: a `limit` problem.
157    #[test]
158    fn rfc8620_limit_example_round_trips() {
159        let body = json!({
160            "type": "urn:ietf:params:jmap:error:limit",
161            "limit": "maxSizeRequest",
162            "status": 400,
163            "detail": "The request is larger than the server is willing to process."
164        });
165        let p: ProblemDetails = serde_json::from_value(body.clone()).unwrap();
166        assert_eq!(p.jmap_error_type(), Some(MethodErrorType::Limit));
167        assert_eq!(p.limit.as_deref(), Some("maxSizeRequest"));
168        assert_eq!(serde_json::to_value(&p).unwrap(), body);
169    }
170
171    /// RFC 9457 §3.1.1: "When this member is not present, its value is
172    /// assumed to be "about:blank"."
173    #[test]
174    fn absent_type_is_about_blank() {
175        let p: ProblemDetails = serde_json::from_value(json!({ "status": 404 })).unwrap();
176        assert_eq!(p.problem_type, ABOUT_BLANK);
177        assert_eq!(p.jmap_error_type(), None);
178    }
179
180    /// RFC 9457 §3.2 extension members round-trip.
181    #[test]
182    fn extension_members_round_trip() {
183        let body = json!({ "type": "about:blank", "requestId": "r1" });
184        let p: ProblemDetails = serde_json::from_value(body.clone()).unwrap();
185        assert_eq!(p.extra["requestId"], "r1");
186        assert_eq!(serde_json::to_value(&p).unwrap(), body);
187    }
188
189    #[test]
190    fn for_jmap_error_limit_without_name_says_unknown() {
191        let mut e = JmapError::limit("x");
192        e.limit_name = None;
193        assert_eq!(
194            ProblemDetails::for_jmap_error(&e, 400).limit.as_deref(),
195            Some("unknown")
196        );
197    }
198}