Skip to main content

jmap_server/
response.rs

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