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