Skip to main content

jmap_server/
response.rs

1//! HTTP response helpers for JMAP request-level errors (RFC 8620 §3.6.1) and
2//! RFC 9457 problem details for any JMAP HTTP resource
3//! (draft-atwood-jmap-updates-00 §7.2).
4
5use http::{Response, StatusCode, header};
6
7use crate::{Invocation, JmapError};
8use jmap_types::MethodErrorType;
9use jmap_types::problem::ProblemDetails;
10
11/// An HTTP error response with an RFC 9457 problem details body, for any
12/// JMAP HTTP resource (draft-atwood-jmap-updates-00 §7.2: the Session
13/// resource, API, upload, download, event source, WebSocket opening
14/// handshake and extension resources SHOULD all return one on a 4xx or
15/// 5xx).
16///
17/// The `Content-Type` is `application/problem+json`. When the caller
18/// localized `title` or `detail` from the request's Accept-Language
19/// (see [`JmapAccounts::accept_language`](crate::JmapAccounts::accept_language)),
20/// pass the language as `content_language`: it labels the response with
21/// `Content-Language` (RFC 8620 §3.8).
22///
23/// ```rust
24/// use http::StatusCode;
25/// use jmap_types::problem::ProblemDetails;
26///
27/// let resp = jmap_server::problem_response(
28///     StatusCode::UNAUTHORIZED,
29///     &ProblemDetails::for_status(401).with_title("Nicht autorisiert"),
30///     Some("de"),
31/// );
32/// assert_eq!(resp.headers()["content-type"], "application/problem+json");
33/// assert_eq!(resp.headers()["content-language"], "de");
34/// ```
35///
36/// # Panics
37///
38/// Does not panic in practice. Serializing `details` cannot fail (it holds
39/// only strings, an integer and a string-keyed map), and the response is
40/// built from a typed [`StatusCode`], a constant `Content-Type` and a
41/// `Content-Language` that is added only when it parses as a header value.
42pub fn problem_response(
43    status: StatusCode,
44    details: &ProblemDetails,
45    content_language: Option<&str>,
46) -> Response<String> {
47    // ProblemDetails holds only strings, an integer and a string-keyed map:
48    // serialization cannot fail.
49    let body = serde_json::to_string(details).expect("ProblemDetails is infallible");
50    let mut builder = Response::builder()
51        .status(status)
52        .header(header::CONTENT_TYPE, jmap_types::problem::PROBLEM_JSON);
53    if let Some(lang) = content_language
54        && let Ok(value) = header::HeaderValue::from_str(lang)
55    {
56        builder = builder.header(header::CONTENT_LANGUAGE, value);
57    }
58    // The status and the headers set above are valid.
59    builder.body(body).expect("valid status code and headers")
60}
61
62/// Wrap a method-level error as an error `Invocation` for `methodResponses`.
63///
64/// Per RFC 8620 §3.6.2, error invocations always use `"error"` as the method
65/// name regardless of the original method.  Only `call_id` is echoed.
66/// Method-level errors are returned inside `methodResponses` with HTTP 200 —
67/// they are NOT returned as top-level HTTP errors.
68///
69/// # Panics
70///
71/// Panics if `err` does not serialize to JSON. The derived `Serialize` for
72/// [`JmapError`] writes only a type string, optional string and integer
73/// fields and a string-keyed map of extra properties, none of which can
74/// fail, so this does not happen; the test
75/// `jmap_error_all_constructors_serialize` covers every constructor. A panic
76/// here would mean a change to [`JmapError`] broke that invariant.
77pub fn error_invocation(call_id: &str, err: JmapError) -> Invocation {
78    // JmapError uses #[derive(Serialize)] over a type string
79    // (MethodErrorType), Option<String> and Option<u64> fields and a
80    // string-keyed `extra` map: all JSON-serializable with string keys.
81    // serde_json::to_value only fails when a Serialize impl produces a
82    // non-string map key; the derived impl for JmapError cannot do this. The
83    // exhaustive contract test `jmap_error_all_constructors_serialize` in
84    // this module exercises every public JmapError constructor and proves
85    // the invariant.
86    //
87    // bd:JMAP-jfia.35 — previously this was an `unwrap_or_else` fallback to
88    // a generic serverFail. That fallback was actively harmful: a future
89    // jmap-types change that broke the Serialize invariant would silently
90    // rewrite the original error to "internal error" with no log signal.
91    // `.expect()` instead lets a panic surface, get caught by the
92    // dispatcher's `task::spawn` isolation, and produce a serverFail
93    // invocation with the failing-variant identity visible in the panic
94    // payload. Louder is safer than silent corruption.
95    let err_value = serde_json::to_value(&err)
96        .expect("JmapError Serialize invariant — see jmap_error_all_constructors_serialize");
97    Invocation::new("error", err_value, call_id)
98}
99
100/// Map a [`JmapError`] type string to the appropriate HTTP status code.
101///
102/// Error type strings are per RFC 8620 §7.1.
103///
104/// # Request-level errors only
105///
106/// Only request-level errors should flow through this function.  Method-level
107/// errors (`accountNotFound`, `notFound`, `unknownMethod`, etc.) belong in
108/// `methodResponses` at HTTP 200 via [`error_invocation`] — they must never
109/// reach `error_status`.  Passing a method-level error here is a caller bug;
110/// the catch-all maps unrecognized types to 500 rather than silently returning
111/// a wrong status code.
112///
113/// Request-level error types (safe to pass here): `notJSON`, `notRequest`,
114/// `limit`, `unknownCapability`, `invalidArguments`, `requestTooLarge`,
115/// `forbidden`, `serverFail`, `serverUnavailable`.
116pub fn error_status(err: &JmapError) -> StatusCode {
117    match err.error_type {
118        // RFC 8620 §3.6.1 request-level errors → 400.
119        MethodErrorType::NotJson
120        | MethodErrorType::NotRequest
121        | MethodErrorType::Limit
122        | MethodErrorType::UnknownCapability
123        | MethodErrorType::InvalidArguments
124        | MethodErrorType::RequestTooLarge => StatusCode::BAD_REQUEST,
125        MethodErrorType::Forbidden => StatusCode::FORBIDDEN,
126        MethodErrorType::ServerFail => StatusCode::INTERNAL_SERVER_ERROR,
127        MethodErrorType::ServerUnavailable => StatusCode::SERVICE_UNAVAILABLE,
128        // Any unrecognized type is an internal bug, not a client error.
129        // The most common mistake is passing a method-level error (e.g. "accountNotFound",
130        // "notFound") to request_error() — those must stay in methodResponses at HTTP 200
131        // via error_invocation() per RFC 8620 §3.6.2.
132        _ => StatusCode::INTERNAL_SERVER_ERROR,
133    }
134}
135
136/// A request-level JMAP error response: HTTP status code + JMAP error body.
137///
138/// Used when an error occurs before method dispatch (e.g., parse failure,
139/// unknown capability).  Derives the HTTP status from the error type via
140/// [`error_status`].  Use [`request_error`] to construct.
141///
142/// Call [`RequestError::into_response`] to produce an `http::Response<String>`
143/// with the RFC 9457 problem details body.  Any HTTP framework that works with
144/// the `http` crate (axum, hyper, warp, etc.) accepts this directly.
145#[derive(Debug)]
146// bd:JMAP-wlip.31 — both fields are private today, so #[non_exhaustive]
147// is functionally a no-op for outside-crate construction / matching.
148// Kept deliberately as a forward-compat signal: a future field that
149// becomes `pub` (e.g. an `extras` map paralleling SetError.extra) does
150// NOT then need to add the attribute as a separate change. The
151// attribute also documents intent at the type-definition site without
152// requiring readers to chase down the field visibility.
153#[non_exhaustive]
154pub struct RequestError {
155    status: StatusCode,
156    err: JmapError,
157}
158
159impl std::fmt::Display for RequestError {
160    /// Render as `"<status>: <error_type>[: <description>]"` for log/diagnostic
161    /// output. The HTTP status is included because [`RequestError`] is the
162    /// request-level error type and the status is the most actionable field
163    /// for operators.
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        match self.err.description.as_deref() {
166            Some(desc) => write!(
167                f,
168                "{}: {}: {}",
169                self.status.as_u16(),
170                self.err.error_type,
171                desc
172            ),
173            None => write!(f, "{}: {}", self.status.as_u16(), self.err.error_type),
174        }
175    }
176}
177
178impl std::error::Error for RequestError {}
179
180impl RequestError {
181    /// The RFC 9457 problem details of this error (RFC 8620 §3.6.1): type
182    /// `urn:ietf:params:jmap:error:<type>`, `status`, `detail` from the
183    /// description, and `limit` for `limit` errors. Add a localized `title`
184    /// and send it with [`problem_response`].
185    pub fn problem_details(&self) -> ProblemDetails {
186        ProblemDetails::for_jmap_error(&self.err, self.status.as_u16())
187    }
188
189    /// The HTTP status code.
190    pub fn status(&self) -> StatusCode {
191        self.status
192    }
193
194    /// Convert into an HTTP response with an RFC 9457 problem details body
195    /// ([`Self::problem_details`], [`problem_response`]) and no
196    /// `Content-Language`.
197    pub fn into_response(self) -> Response<String> {
198        problem_response(self.status, &self.problem_details(), None)
199    }
200}
201
202/// Convenience constructor: wrap a [`JmapError`] in a [`RequestError`],
203/// deriving the HTTP status code automatically.
204///
205/// # Request-level errors only
206///
207/// Pass only request-level errors (see [`error_status`] for the full list).
208/// Method-level errors must go through [`error_invocation`] instead.
209pub fn request_error(err: JmapError) -> RequestError {
210    let status = error_status(&err);
211    RequestError { status, err }
212}
213
214impl From<JmapError> for RequestError {
215    /// Convert a [`JmapError`] into a [`RequestError`], deriving the HTTP
216    /// status code automatically via [`error_status`].
217    ///
218    /// Enables `?` propagation in functions returning `Result<_, RequestError>`.
219    /// Pass only request-level errors; see [`error_status`] for the safe list.
220    fn from(err: JmapError) -> Self {
221        request_error(err)
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228    use http::StatusCode;
229
230    // -----------------------------------------------------------------------
231    // error_invocation
232    // -----------------------------------------------------------------------
233
234    /// Oracle: RFC 8620 §3.6.2 — error invocations must use the literal method name "error".
235    /// The call_id must be echoed from the request.
236    #[test]
237    fn error_invocation_structure() {
238        let inv = error_invocation("c0", JmapError::unknown_method());
239        assert_eq!(inv.name, "error");
240        assert_eq!(inv.call_id, "c0");
241    }
242
243    /// Oracle: RFC 8620 §7.1 — error args object must have a "type" field.
244    #[test]
245    fn error_invocation_args_contains_type() {
246        let inv = error_invocation("c0", JmapError::unknown_method());
247        // inv.arguments is already a serde_json::Value — index directly.
248        assert_eq!(inv.arguments["type"], "unknownMethod");
249    }
250
251    /// Oracle: RFC 8620 §7.1 — serverFail error type string and description field.
252    #[test]
253    fn error_invocation_server_fail() {
254        let inv = error_invocation("y", JmapError::server_fail("boom"));
255        assert_eq!(inv.arguments["type"], "serverFail");
256        assert_eq!(inv.arguments["description"], "boom");
257    }
258
259    // -----------------------------------------------------------------------
260    // error_status
261    // -----------------------------------------------------------------------
262
263    /// Oracle: RFC 8620 §3.6.1 — unknownCapability is a request-level error → 400.
264    #[test]
265    fn error_status_unknown_capability_is_400() {
266        let e: JmapError =
267            serde_json::from_value(serde_json::json!({"type": "unknownCapability"})).unwrap();
268        assert_eq!(error_status(&e), StatusCode::BAD_REQUEST);
269    }
270
271    /// Oracle: RFC 8620 §7.1 — invalidArguments → 400.
272    #[test]
273    fn error_status_invalid_arguments_is_400() {
274        assert_eq!(
275            error_status(&JmapError::invalid_arguments("x")),
276            StatusCode::BAD_REQUEST
277        );
278    }
279
280    /// Oracle: RFC 8620 §3.6.1 limit concept — requestTooLarge → 400.
281    #[test]
282    fn error_status_request_too_large_is_400() {
283        assert_eq!(
284            error_status(&JmapError::request_too_large()),
285            StatusCode::BAD_REQUEST
286        );
287    }
288
289    /// Oracle: RFC 8620 §7.1 — forbidden → HTTP 403.
290    #[test]
291    fn error_status_forbidden_is_403() {
292        assert_eq!(error_status(&JmapError::forbidden()), StatusCode::FORBIDDEN);
293    }
294
295    /// Oracle: RFC 8620 §3.6.1 — accountNotFound is method-level (stays HTTP 200 in
296    /// methodResponses).  Passing it to error_status is a caller bug; the catch-all
297    /// maps it to 500 rather than silently returning a wrong HTTP status.
298    #[test]
299    fn error_status_account_not_found_is_500() {
300        assert_eq!(
301            error_status(&JmapError::account_not_found()),
302            StatusCode::INTERNAL_SERVER_ERROR
303        );
304    }
305
306    /// Oracle: RFC 8620 §7.1 — serverFail → HTTP 500.
307    #[test]
308    fn error_status_server_fail_is_500() {
309        assert_eq!(
310            error_status(&JmapError::server_fail("x")),
311            StatusCode::INTERNAL_SERVER_ERROR
312        );
313    }
314
315    /// Oracle: unknown error types are server-side bugs, not client mistakes → 500.
316    #[test]
317    fn error_status_unknown_type_is_500() {
318        let e: JmapError =
319            serde_json::from_value(serde_json::json!({"type": "totallyMadeUp"})).unwrap();
320        assert_eq!(error_status(&e), StatusCode::INTERNAL_SERVER_ERROR);
321    }
322
323    // -----------------------------------------------------------------------
324    // RequestError / request_error
325    // -----------------------------------------------------------------------
326
327    /// Oracle: request_error calls error_status to derive the HTTP status code.
328    #[test]
329    fn request_error_derives_status() {
330        let re = request_error(JmapError::invalid_arguments("bad"));
331        assert_eq!(re.into_response().status(), StatusCode::BAD_REQUEST);
332    }
333
334    /// Oracle: IntoResponse for RequestError must set HTTP status from the contained StatusCode.
335    #[test]
336    fn request_error_into_response_status_code() {
337        let re = request_error(JmapError::invalid_arguments("bad"));
338        let resp = re.into_response();
339        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
340    }
341
342    /// Oracle: RFC 8620 §3.6.1 + RFC 9457 §3 — Content-Type must be application/problem+json.
343    #[test]
344    fn request_error_content_type_is_problem_json() {
345        let re = request_error(JmapError::not_request());
346        let resp = re.into_response();
347        assert_eq!(
348            resp.headers()
349                .get(header::CONTENT_TYPE)
350                .and_then(|v| v.to_str().ok()),
351            Some("application/problem+json"),
352            "Content-Type must be application/problem+json per RFC 9457"
353        );
354    }
355
356    /// Oracle: RFC 8620 §3.6.1 — type field must be a full URN.
357    #[test]
358    fn request_error_type_is_full_urn() {
359        let body: serde_json::Value = serde_json::from_str(
360            &request_error(JmapError::not_request())
361                .into_response()
362                .into_body(),
363        )
364        .unwrap();
365        assert_eq!(
366            body["type"], "urn:ietf:params:jmap:error:notRequest",
367            "type must be full URN"
368        );
369    }
370
371    /// Oracle: RFC 9457 §3.1.2 — status field must equal the HTTP status code.
372    #[test]
373    fn request_error_status_field_matches_http_status() {
374        let body: serde_json::Value = serde_json::from_str(
375            &request_error(JmapError::not_request())
376                .into_response()
377                .into_body(),
378        )
379        .unwrap();
380        assert_eq!(body["status"], 400, "status field must match HTTP code");
381    }
382
383    /// Oracle: RFC 8620 §3.6.1 — limit errors MUST include "limit" property.
384    #[test]
385    fn request_error_limit_includes_limit_property() {
386        let body: serde_json::Value = serde_json::from_str(
387            &request_error(JmapError::limit("maxCallsInRequest"))
388                .into_response()
389                .into_body(),
390        )
391        .unwrap();
392        assert_eq!(
393            body["limit"], "maxCallsInRequest",
394            "limit property must name the exceeded limit"
395        );
396        assert_eq!(body["type"], "urn:ietf:params:jmap:error:limit");
397    }
398
399    /// Oracle: RFC 8620 §3.6.1 ("limit" property naming the limit) and
400    /// RFC 9457 §3.1.4 ("detail"). A limit error with a description carries
401    /// both. Expected object is hand-written.
402    #[test]
403    fn request_error_limit_with_description_includes_limit_and_detail() {
404        let mut err = JmapError::limit("maxCallsInRequest");
405        err.description = Some("17 calls exceed 16".to_owned());
406        let body: serde_json::Value =
407            serde_json::from_str(&request_error(err).into_response().into_body()).unwrap();
408        assert_eq!(
409            body,
410            serde_json::json!({
411                "type": "urn:ietf:params:jmap:error:limit",
412                "status": 400,
413                "limit": "maxCallsInRequest",
414                "detail": "17 calls exceed 16",
415            })
416        );
417    }
418
419    // -----------------------------------------------------------------------
420    // JmapError serialization invariant (guards the .expect() in error_invocation)
421    // -----------------------------------------------------------------------
422
423    /// Oracle: error_invocation depends on JmapError being infallibly serializable.
424    /// This test exercises every JmapError constructor to catch any future regression
425    /// in jmap-types that breaks the invariant.
426    #[test]
427    fn jmap_error_all_constructors_serialize() {
428        let errors = vec![
429            JmapError::not_json(),
430            JmapError::not_request(),
431            JmapError::limit("maxCallsInRequest"),
432            JmapError::unknown_capability_with_detail("urn:example:unknown"),
433            JmapError::forbidden(),
434            JmapError::server_fail("test"),
435            JmapError::server_unavailable(),
436            JmapError::server_partial_fail(),
437            JmapError::unknown_method(),
438            JmapError::invalid_arguments("x"),
439            JmapError::invalid_result_reference(),
440            JmapError::account_not_found(),
441            JmapError::account_not_supported_by_method(),
442            JmapError::account_read_only(),
443            JmapError::request_too_large(),
444            JmapError::too_large(),
445            JmapError::rate_limit(),
446            JmapError::state_mismatch(),
447            JmapError::cannot_calculate_changes(),
448            JmapError::anchor_not_found(),
449            JmapError::unsupported_sort(),
450            JmapError::unsupported_filter(),
451            JmapError::too_many_changes_with_limit(100),
452            JmapError::from_account_not_found(),
453            JmapError::from_account_not_supported_by_method(),
454            JmapError::custom("customErrorType"),
455        ];
456        for err in &errors {
457            let v = serde_json::to_value(err);
458            assert!(v.is_ok(), "JmapError variant failed to serialize: {err:?}");
459        }
460    }
461
462    // -----------------------------------------------------------------------
463    // From<JmapError> for RequestError
464    // -----------------------------------------------------------------------
465
466    /// Oracle: From<JmapError> must produce the same result as request_error().
467    #[test]
468    fn from_jmap_error_matches_request_error() {
469        let via_from: RequestError = JmapError::invalid_arguments("x").into();
470        let via_fn = request_error(JmapError::invalid_arguments("x"));
471        assert_eq!(
472            via_from.into_response().status(),
473            via_fn.into_response().status()
474        );
475    }
476}