Skip to main content

navree_http/
error.rs

1//! [`AppError`]: every HTTP error, rendered in Navree's JSON error shape.
2
3use std::any::Any;
4use std::collections::BTreeMap;
5use std::error::Error as StdError;
6use std::fmt;
7use std::sync::{Arc, Mutex, PoisonError};
8use std::time::Duration;
9
10use http::header::{CONTENT_TYPE, HeaderName, HeaderValue, RETRY_AFTER, X_CONTENT_TYPE_OPTIONS};
11use http::{HeaderMap, StatusCode};
12use navree_kernel::__private::is_app_module;
13use navree_kernel::{AppContext, BoxError};
14use serde::Serialize;
15
16use crate::body::Body;
17use crate::codes;
18use crate::options::ErrorOptions;
19use crate::response::{IntoResponse, Response};
20
21/// The content type of every error response.
22pub const ERROR_CONTENT_TYPE: &str = "application/json";
23
24/// The default message of a 500: internals never reach the client.
25const INTERNAL_MESSAGE: &str = "Internal server error";
26
27/// The result type of handlers: `Result<T>` fails with an [`AppError`].
28pub type Result<T, E = AppError> = std::result::Result<T, E>;
29
30/// An HTTP error. Handlers, extractors, guards and layers return it; it
31/// renders in Navree's JSON error shape, as `application/json`:
32///
33/// ```json
34/// {"statusCode": 404, "message": "Deal not found", "error": "Not Found", "code": "not_found"}
35/// ```
36///
37/// - `statusCode` is the HTTP status.
38/// - `message` is the [`detail`](AppError::detail) when there is one, else
39///   the [`title`](AppError::title) (the reason phrase by default, and
40///   `"Internal server error"` for 500s). For validation errors it is every
41///   field message, flattened in field order.
42/// - `error` is the reason phrase of the status (`"Not Found"`).
43/// - `code` is the machine-readable [`code`](AppError::code) a front end
44///   maps to a translation key: one of the framework's stable
45///   [`codes`](crate::codes), or an app's own
46///   ([`with_code`](AppError::with_code)). `http.errors.code = false`
47///   leaves it out.
48/// - `errors` (validation errors only) maps fields to their messages:
49///
50/// ```json
51/// {"statusCode": 400, "message": ["email must be a valid email address"],
52///  "error": "Bad Request", "code": "validation_failed",
53///  "errors": {"email": ["email must be a valid email address"]}}
54/// ```
55///
56/// The request id is in the `X-Request-Id` response header, not the body.
57/// Any error type converts into a 500 with `?` (its message is logged,
58/// never sent); modules turn their own error types into specific statuses
59/// with [`ModuleBuilderHttpExt::map_error`](crate::ModuleBuilderHttpExt::map_error).
60///
61/// `AppError` deliberately does not implement `std::error::Error`, which is
62/// what makes the blanket `From<E: Into<BoxError>>` conversion possible.
63pub struct AppError {
64    /// The HTTP status.
65    pub status: StatusCode,
66    /// The machine-readable code, rendered as `code` (`"not_found"`,
67    /// `"validation_failed"`, `"campaign_already_running"`): lower snake
68    /// case, stable across releases, what a front end maps to a translation
69    /// key. Empty leaves the member out.
70    pub code: String,
71    /// The default message, rendered as `message` when there is no
72    /// [`detail`](AppError::detail): the reason phrase for statuses built
73    /// with [`from_status`](AppError::from_status).
74    pub title: String,
75    /// A human-readable explanation of this occurrence, rendered as
76    /// `message`.
77    pub detail: Option<String>,
78    /// Field errors (`{"field.path": ["message"]}`), for 400 validation
79    /// responses. Boxed, like `headers`, to keep `Result<T, AppError>` small.
80    pub errors: Option<Box<BTreeMap<String, Vec<String>>>>,
81    /// Extra response headers (`Retry-After`, `WWW-Authenticate`, ...).
82    pub headers: Box<HeaderMap>,
83    /// The underlying error, logged for 5xx responses and never sent.
84    pub source: Option<BoxError>,
85}
86
87impl AppError {
88    /// An error with an explicit status, code and title (the default
89    /// message).
90    pub fn new(status: StatusCode, code: impl Into<String>, title: impl Into<String>) -> Self {
91        Self {
92            status,
93            code: code.into(),
94            title: title.into(),
95            detail: None,
96            errors: None,
97            headers: Box::default(),
98            source: None,
99        }
100    }
101
102    /// The default error for `status`: its reason phrase as the title, and
103    /// a code derived from it.
104    pub fn from_status(status: StatusCode) -> Self {
105        let reason = status.canonical_reason().unwrap_or("Error");
106        match status.as_u16() {
107            401 => Self::new(status, codes::UNAUTHENTICATED, reason),
108            500 => Self::new(status, codes::INTERNAL_ERROR, INTERNAL_MESSAGE),
109            _ => Self::new(status, slug(reason), reason),
110        }
111    }
112
113    /// 400 with a message.
114    pub fn bad_request(detail: impl Into<String>) -> Self {
115        Self::from_status(StatusCode::BAD_REQUEST).with_detail(detail)
116    }
117
118    /// 400 `invalid_filter` with a message: a list filter that names an
119    /// unknown field or has a malformed value.
120    pub fn invalid_filter(detail: impl Into<String>) -> Self {
121        Self::bad_request(detail).with_code(codes::INVALID_FILTER)
122    }
123
124    /// 401: the request is not authenticated.
125    pub fn unauthenticated() -> Self {
126        Self::from_status(StatusCode::UNAUTHORIZED)
127    }
128
129    /// 401 `two_factor_required` `"Two-factor authentication required"`:
130    /// the password was right, and the account also needs a second factor.
131    pub fn two_factor_required() -> Self {
132        Self::unauthenticated()
133            .with_code(codes::TWO_FACTOR_REQUIRED)
134            .with_detail("Two-factor authentication required")
135    }
136
137    /// 403: the user may not do this.
138    pub fn forbidden() -> Self {
139        Self::from_status(StatusCode::FORBIDDEN)
140    }
141
142    /// 404.
143    pub fn not_found() -> Self {
144        Self::from_status(StatusCode::NOT_FOUND)
145    }
146
147    /// 409 with a message.
148    pub fn conflict(detail: impl Into<String>) -> Self {
149        Self::from_status(StatusCode::CONFLICT).with_detail(detail)
150    }
151
152    /// 409 `limit_reached` with a message: a plan or quota limit stops the
153    /// change (seats, projects, monthly sends).
154    pub fn limit_reached(detail: impl Into<String>) -> Self {
155        Self::conflict(detail).with_code(codes::LIMIT_REACHED)
156    }
157
158    /// 403 `demo_read_only` `"Demo workspaces are read-only."`: a write in a
159    /// workspace that only shows sample data.
160    pub fn demo_read_only() -> Self {
161        Self::forbidden()
162            .with_code(codes::DEMO_READ_ONLY)
163            .with_detail("Demo workspaces are read-only.")
164    }
165
166    /// 403 `"Invalid CSRF token"`: the CSRF token is missing or does not
167    /// match the session.
168    pub fn csrf_mismatch() -> Self {
169        Self::new(
170            StatusCode::FORBIDDEN,
171            codes::CSRF_TOKEN_MISMATCH,
172            "Invalid CSRF token",
173        )
174    }
175
176    /// 419 `page_expired` `"Page Expired"`: the page was open too long, or the
177    /// session it belongs to changed, so what it sends can't be trusted. The
178    /// user reloads and tries again.
179    pub fn page_expired() -> Self {
180        Self::new(
181            StatusCode::from_u16(419).unwrap_or(StatusCode::BAD_REQUEST),
182            codes::PAGE_EXPIRED,
183            "Page Expired",
184        )
185    }
186
187    /// 400 with field errors (`{"field.path": ["message"]}`): `message` is
188    /// every field message, flattened in field order, and `errors` the map.
189    pub fn validation(errors: BTreeMap<String, Vec<String>>) -> Self {
190        let mut error = Self::new(
191            StatusCode::BAD_REQUEST,
192            codes::VALIDATION_FAILED,
193            "Bad Request",
194        );
195        error.errors = Some(Box::new(errors));
196        error
197    }
198
199    /// 413: the request body is larger than `limit` bytes.
200    pub fn payload_too_large(limit: usize) -> Self {
201        Self::from_status(StatusCode::PAYLOAD_TOO_LARGE)
202            .with_detail(format!("The request body must not exceed {limit} bytes."))
203    }
204
205    /// 429 with a `Retry-After` header (whole seconds, at least 1).
206    pub fn too_many_requests(retry_after: Duration) -> Self {
207        let secs = retry_after_secs(retry_after);
208        Self::from_status(StatusCode::TOO_MANY_REQUESTS)
209            .with_header(RETRY_AFTER, HeaderValue::from(secs))
210    }
211
212    /// 503 with a message.
213    pub fn service_unavailable(detail: impl Into<String>) -> Self {
214        Self::from_status(StatusCode::SERVICE_UNAVAILABLE).with_detail(detail)
215    }
216
217    /// 500 caused by `err`. The client sees `"Internal server error"`; the
218    /// error is logged.
219    pub fn internal(err: impl Into<BoxError>) -> Self {
220        let mut error = Self::from_status(StatusCode::INTERNAL_SERVER_ERROR);
221        error.source = Some(err.into());
222        error
223    }
224
225    /// Sets the message.
226    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
227        self.detail = Some(detail.into());
228        self
229    }
230
231    /// Sets the machine-readable `code` (lower snake case, such as
232    /// `campaign_already_running`); the status and the message stay.
233    pub fn with_code(mut self, code: impl Into<String>) -> Self {
234        self.code = code.into();
235        self
236    }
237
238    /// Adds a response header.
239    pub fn with_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
240        self.headers.insert(name, value);
241        self
242    }
243
244    /// Records the underlying error (logged for 5xx responses, never sent).
245    pub fn with_source(mut self, source: impl Into<BoxError>) -> Self {
246        self.source = Some(source.into());
247        self
248    }
249
250    /// The response body:
251    /// `{"statusCode", "message", "error", "code"}`, plus `"errors"` for
252    /// validation errors.
253    pub fn body(&self) -> serde_json::Value {
254        self.body_as(ErrorFormat::default())
255    }
256
257    /// The response body in `format`.
258    pub(crate) fn body_as(&self, format: ErrorFormat) -> serde_json::Value {
259        serde_json::to_value(self.wire(format)).unwrap_or_default()
260    }
261
262    fn wire(&self, format: ErrorFormat) -> ErrorBody<'_> {
263        let errors = self.errors.as_deref();
264        let message = match errors {
265            Some(errors) if !errors.is_empty() => {
266                Message::Many(errors.values().flatten().map(String::as_str).collect())
267            }
268            _ => Message::One(self.detail.as_deref().unwrap_or(&self.title)),
269        };
270        let code = (format.code && !self.code.is_empty()).then_some(self.code.as_str());
271        ErrorBody {
272            status_code: self.status.as_u16(),
273            message,
274            error: self.status.canonical_reason().unwrap_or(&self.title),
275            code,
276            errors,
277        }
278    }
279
280    /// Takes the error out of a response rendered by
281    /// [`into_response`](IntoResponse::into_response), so a pipeline other
282    /// than the HTTP server's (navree-micro's message handlers) can map and
283    /// log it the way the HTTP error layer does. `None` for any other
284    /// response, and once the error has been taken.
285    pub fn take_from(response: &mut Response) -> Option<AppError> {
286        response
287            .extensions_mut()
288            .remove::<PendingError>()
289            .and_then(|pending| pending.take())
290    }
291
292    /// Renders the response in `format` (the pipeline sets `X-Request-Id`
293    /// itself).
294    pub(crate) fn render(&self, format: ErrorFormat) -> Response {
295        let body = serde_json::to_vec(&self.wire(format)).unwrap_or_default();
296        let mut response = Response::new(Body::from(body));
297        *response.status_mut() = self.status;
298        let headers = response.headers_mut();
299        for (name, value) in self.headers.iter() {
300            headers.insert(name, value.clone());
301        }
302        headers.insert(CONTENT_TYPE, HeaderValue::from_static(ERROR_CONTENT_TYPE));
303        headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
304        response
305    }
306
307    /// An extractor rejection (or a plain-text error response) with
308    /// `status` and `text`: a client error shows `text` as its message, a
309    /// server error logs it. A 422 (well-formed JSON of the wrong shape) is a
310    /// 400, like every other input error.
311    pub(crate) fn rejection(status: StatusCode, text: impl Into<String>) -> Self {
312        let status = if status == StatusCode::UNPROCESSABLE_ENTITY {
313            StatusCode::BAD_REQUEST
314        } else {
315            status
316        };
317        let error = Self::from_status(status);
318        let text = text.into();
319        let text = text.trim();
320        if text.is_empty() {
321            error
322        } else if status.is_client_error() {
323            error.with_detail(text)
324        } else {
325            error.with_source(text.to_owned())
326        }
327    }
328
329    /// The error and its source chain, for logs.
330    pub(crate) fn log_chain(&self) -> String {
331        let mut out = format!("{} {}", self.status.as_u16(), self.title);
332        if let Some(detail) = &self.detail {
333            out.push_str(": ");
334            out.push_str(detail);
335        }
336        let mut next: Option<&(dyn StdError + 'static)> = self
337            .source
338            .as_deref()
339            .map(|e| e as &(dyn StdError + 'static));
340        while let Some(error) = next {
341            out.push_str(": ");
342            out.push_str(&error.to_string());
343            next = error.source();
344        }
345        out
346    }
347}
348
349/// `Retry-After` in whole seconds, rounded up, at least 1.
350pub(crate) fn retry_after_secs(d: Duration) -> u64 {
351    let secs = d.as_secs() + u64::from(d.subsec_nanos() > 0);
352    secs.max(1)
353}
354
355/// `"Payment Required"` → `"payment_required"`.
356fn slug(title: &str) -> String {
357    title
358        .chars()
359        .map(|c| {
360            if c.is_ascii_alphanumeric() {
361                c.to_ascii_lowercase()
362            } else {
363                '_'
364            }
365        })
366        .collect()
367}
368
369/// How error bodies are rendered: `http.errors`, read once at boot.
370#[derive(Clone, Copy, Debug)]
371pub(crate) struct ErrorFormat {
372    /// Render the `code` member (`http.errors.code`).
373    pub(crate) code: bool,
374}
375
376impl Default for ErrorFormat {
377    fn default() -> Self {
378        Self { code: true }
379    }
380}
381
382impl From<&ErrorOptions> for ErrorFormat {
383    fn from(options: &ErrorOptions) -> Self {
384        Self { code: options.code }
385    }
386}
387
388/// The wire format, members in their documented order.
389#[derive(Serialize)]
390#[serde(rename_all = "camelCase")]
391struct ErrorBody<'a> {
392    status_code: u16,
393    message: Message<'a>,
394    error: &'a str,
395    #[serde(skip_serializing_if = "Option::is_none")]
396    code: Option<&'a str>,
397    #[serde(skip_serializing_if = "Option::is_none")]
398    errors: Option<&'a BTreeMap<String, Vec<String>>>,
399}
400
401/// `message`: one string, or every validation message.
402#[derive(Serialize)]
403#[serde(untagged)]
404enum Message<'a> {
405    One(&'a str),
406    Many(Vec<&'a str>),
407}
408
409impl fmt::Debug for AppError {
410    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411        f.debug_struct("AppError")
412            .field("status", &self.status)
413            .field("code", &self.code)
414            .field("title", &self.title)
415            .field("detail", &self.detail)
416            .field("errors", &self.errors)
417            .field("source", &self.source)
418            .finish_non_exhaustive()
419    }
420}
421
422impl fmt::Display for AppError {
423    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
424        write!(f, "{} {}", self.status.as_u16(), self.title)?;
425        if let Some(detail) = &self.detail {
426            write!(f, ": {detail}")?;
427        }
428        Ok(())
429    }
430}
431
432/// Any error converts into a 500 (`?` in handlers), like `anyhow`.
433impl<E: Into<BoxError>> From<E> for AppError {
434    fn from(error: E) -> Self {
435        Self::internal(error)
436    }
437}
438
439/// The rendered response carries the error itself, so the pipeline can map
440/// and log it.
441impl IntoResponse for AppError {
442    fn into_response(self) -> Response {
443        let mut response = self.render(ErrorFormat::default());
444        response
445            .extensions_mut()
446            .insert(PendingError(Arc::new(Mutex::new(Some(self)))));
447        response
448    }
449}
450
451/// An [`AppError`] travelling in response extensions until the error layer
452/// maps, logs and renders it.
453#[derive(Clone)]
454pub(crate) struct PendingError(Arc<Mutex<Option<AppError>>>);
455
456impl PendingError {
457    pub(crate) fn take(&self) -> Option<AppError> {
458        self.0.lock().unwrap_or_else(PoisonError::into_inner).take()
459    }
460}
461
462/// Maps errors of one type (anywhere in an [`AppError`]'s source chain) to a
463/// specific [`AppError`]. Contributed with
464/// [`ModuleBuilderHttpExt::map_error`](crate::ModuleBuilderHttpExt::map_error).
465#[derive(Clone)]
466pub struct ErrorMapper {
467    type_name: &'static str,
468    map: Arc<MapFn>,
469    map_any: Arc<MapAnyFn>,
470}
471
472type MapFn = dyn Fn(&(dyn StdError + 'static)) -> Option<AppError> + Send + Sync;
473
474type MapAnyFn = dyn Fn(&(dyn Any + Send + Sync)) -> Option<AppError> + Send + Sync;
475
476impl ErrorMapper {
477    /// A mapper for errors of type `E`; returning `None` keeps the 500.
478    pub fn new<E: StdError + 'static>(f: fn(&E) -> Option<AppError>) -> Self {
479        Self {
480            type_name: std::any::type_name::<E>(),
481            map: Arc::new(move |error| error.downcast_ref::<E>().and_then(f)),
482            map_any: Arc::new(move |error| error.downcast_ref::<E>().and_then(f)),
483        }
484    }
485
486    /// Applies the first matching mapper to `error`'s source chain; `None`
487    /// when no mapper matches. The HTTP pipeline does this for every 500
488    /// with a source; other protocols (navree-grpc) and code that reports
489    /// errors outside a response (MCP tool results, for example) collect the
490    /// app's mappers with `ctx.contributions::<ErrorMapper>()` and call it
491    /// too.
492    ///
493    /// ```
494    /// use http::StatusCode;
495    /// use navree_http::{AppError, ErrorMapper};
496    ///
497    /// #[derive(Debug)]
498    /// struct Missing;
499    ///
500    /// impl std::fmt::Display for Missing {
501    ///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
502    ///         f.write_str("missing")
503    ///     }
504    /// }
505    ///
506    /// impl std::error::Error for Missing {}
507    ///
508    /// let mappers = [ErrorMapper::new(|_: &Missing| Some(AppError::not_found()))];
509    /// let mapped = ErrorMapper::apply(&mappers, &AppError::internal(Missing)).unwrap();
510    /// assert_eq!(mapped.status, StatusCode::NOT_FOUND);
511    /// assert!(ErrorMapper::apply(&mappers, &AppError::internal("other")).is_none());
512    /// ```
513    pub fn apply(mappers: &[ErrorMapper], error: &AppError) -> Option<AppError> {
514        error
515            .source
516            .as_deref()
517            .and_then(|source| Self::apply_to(mappers, source))
518    }
519
520    /// Applies the first matching mapper to `error` and then to its source
521    /// chain.
522    pub fn apply_to(mappers: &[ErrorMapper], error: &(dyn StdError + 'static)) -> Option<AppError> {
523        let mut next = Some(error);
524        while let Some(cause) = next {
525            for mapper in mappers {
526                if let Some(mapped) = (mapper.map)(cause) {
527                    return Some(mapped);
528                }
529            }
530            next = cause.source();
531        }
532        None
533    }
534
535    /// Applies the first mapper whose error type `error` is, for errors held
536    /// as `dyn Any` (a GraphQL resolver error keeps its source that way).
537    pub fn apply_any(mappers: &[ErrorMapper], error: &(dyn Any + Send + Sync)) -> Option<AppError> {
538        mappers.iter().find_map(|mapper| (mapper.map_any)(error))
539    }
540}
541
542impl fmt::Debug for ErrorMapper {
543    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544        f.debug_struct("ErrorMapper")
545            .field("error_type", &self.type_name)
546            .finish()
547    }
548}
549
550/// The refusal of each [`ErrorMapper`] that a module acting for a plugin the kernel does not
551/// find first-party contributes for an error type of another crate, in module order: such a
552/// mapper answers that error wherever the app's own code raises it, with the plugin's status
553/// and text, and before the app's mapper of the same type when the app imports the plugin. So
554/// only a module of the app maps another crate's errors; a plugin maps the error types of its
555/// own crate. An app whose mappers all come from modules that act for no plugin reads nothing
556/// more. navree-micro, navree-mcp, navree-graphql and navree-grpc, which answer their handlers'
557/// errors with the same mappers, refuse them with this in an app with no `HttpModule`.
558pub fn mappers_of_plugins(ctx: &AppContext) -> Vec<String> {
559    let contributed = ctx.contributions::<ErrorMapper>();
560    if contributed
561        .iter()
562        .all(|mapper| is_app_module(ctx, mapper.module.id))
563    {
564        return Vec::new();
565    }
566    let plugins = ctx.plugins().plugins;
567    contributed
568        .iter()
569        .filter_map(|mapper| {
570            let module = mapper.module.id;
571            let plugin = plugins.iter().find(|plugin| {
572                !plugin.first_party && plugin.modules.iter().any(|member| member.id == module)
573            })?;
574            let error = mapper.value.type_name;
575            let outer = error.split_once('<').map_or(error, |(outer, _)| outer);
576            let own = outer
577                .strip_prefix(plugin.info.crate_name)
578                .is_some_and(|rest| rest.starts_with("::"));
579            if own {
580                return None;
581            }
582            let reason = navree_kernel::__private::acts_for_reason(ctx, module);
583            Some(format!(
584                "plugin `{}` answers the app's errors of type `{error}` (m.map_error in `{}`{reason}), a type of another crate; only a module of the app maps another crate's errors: remove the plugin or update it to a version that maps only its own errors, and to use the plugin's mapping, register it from a module of the app (m.map_error)",
585                plugin.info.name, mapper.module.name
586            ))
587        })
588        .collect()
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594
595    /// Clippy's `result_large_err` fires at 128 bytes; every crate returning
596    /// `navree_http::Result<T>` would have to silence it.
597    #[test]
598    fn app_error_stays_small_enough_for_result() {
599        assert!(
600            std::mem::size_of::<AppError>() < 128,
601            "AppError is {} bytes",
602            std::mem::size_of::<AppError>()
603        );
604    }
605
606    #[derive(Debug)]
607    struct Taken;
608
609    impl fmt::Display for Taken {
610        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
611            f.write_str("taken")
612        }
613    }
614
615    impl StdError for Taken {}
616
617    #[derive(Debug)]
618    struct Wrapped(Taken);
619
620    impl fmt::Display for Wrapped {
621        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
622            f.write_str("wrapped")
623        }
624    }
625
626    impl StdError for Wrapped {
627        fn source(&self) -> Option<&(dyn StdError + 'static)> {
628            Some(&self.0)
629        }
630    }
631
632    fn mappers() -> Vec<ErrorMapper> {
633        vec![ErrorMapper::new::<Taken>(|_| {
634            Some(AppError::conflict("already taken"))
635        })]
636    }
637
638    #[test]
639    fn mappers_apply_to_a_source_chain() {
640        let mappers = mappers();
641        let mapped = ErrorMapper::apply(&mappers, &AppError::internal(Wrapped(Taken))).unwrap();
642        assert_eq!(mapped.status, StatusCode::CONFLICT);
643        let mapped = ErrorMapper::apply_to(&mappers, &Wrapped(Taken)).unwrap();
644        assert_eq!(mapped.detail.as_deref(), Some("already taken"));
645        assert!(ErrorMapper::apply(&mappers, &AppError::internal("other")).is_none());
646        assert!(ErrorMapper::apply(&mappers, &AppError::not_found()).is_none());
647    }
648
649    #[test]
650    fn mappers_apply_to_errors_held_as_any() {
651        let mappers = mappers();
652        let held: Arc<dyn Any + Send + Sync> = Arc::new(Taken);
653        let mapped = ErrorMapper::apply_any(&mappers, &*held).unwrap();
654        assert_eq!(mapped.status, StatusCode::CONFLICT);
655        let other: Arc<dyn Any + Send + Sync> = Arc::new(Wrapped(Taken));
656        assert!(ErrorMapper::apply_any(&mappers, &*other).is_none());
657    }
658
659    /// One body snapshot per framework error: the stable `code` follows
660    /// `error`.
661    #[test]
662    fn framework_errors_render_their_stable_codes() {
663        use serde_json::json;
664
665        let errors = BTreeMap::from([(
666            "email".to_owned(),
667            vec!["email must be a valid email address".to_owned()],
668        )]);
669        let cases = [
670            (
671                AppError::bad_request("The export is empty."),
672                json!({"statusCode": 400, "message": "The export is empty.", "error": "Bad Request", "code": "bad_request"}),
673            ),
674            (
675                AppError::validation(errors.clone()),
676                json!({
677                    "statusCode": 400,
678                    "message": ["email must be a valid email address"],
679                    "error": "Bad Request",
680                    "code": "validation_failed",
681                    "errors": {"email": ["email must be a valid email address"]},
682                }),
683            ),
684            (
685                AppError::invalid_filter("Unknown filter `colour`."),
686                json!({"statusCode": 400, "message": "Unknown filter `colour`.", "error": "Bad Request", "code": "invalid_filter"}),
687            ),
688            (
689                AppError::unauthenticated(),
690                json!({"statusCode": 401, "message": "Unauthorized", "error": "Unauthorized", "code": "unauthenticated"}),
691            ),
692            (
693                AppError::two_factor_required(),
694                json!({"statusCode": 401, "message": "Two-factor authentication required", "error": "Unauthorized", "code": "two_factor_required"}),
695            ),
696            (
697                AppError::forbidden(),
698                json!({"statusCode": 403, "message": "Forbidden", "error": "Forbidden", "code": "forbidden"}),
699            ),
700            (
701                AppError::csrf_mismatch(),
702                json!({"statusCode": 403, "message": "Invalid CSRF token", "error": "Forbidden", "code": "csrf_token_mismatch"}),
703            ),
704            (
705                AppError::demo_read_only(),
706                json!({"statusCode": 403, "message": "Demo workspaces are read-only.", "error": "Forbidden", "code": "demo_read_only"}),
707            ),
708            (
709                AppError::not_found(),
710                json!({"statusCode": 404, "message": "Not Found", "error": "Not Found", "code": "not_found"}),
711            ),
712            (
713                AppError::conflict("Email taken"),
714                json!({"statusCode": 409, "message": "Email taken", "error": "Conflict", "code": "conflict"}),
715            ),
716            (
717                AppError::limit_reached("Your plan includes 5 seats."),
718                json!({"statusCode": 409, "message": "Your plan includes 5 seats.", "error": "Conflict", "code": "limit_reached"}),
719            ),
720            (
721                AppError::payload_too_large(16),
722                json!({"statusCode": 413, "message": "The request body must not exceed 16 bytes.", "error": "Payload Too Large", "code": "payload_too_large"}),
723            ),
724            (
725                AppError::page_expired(),
726                json!({"statusCode": 419, "message": "Page Expired", "error": "Page Expired", "code": "page_expired"}),
727            ),
728            (
729                AppError::too_many_requests(Duration::from_secs(3)),
730                json!({"statusCode": 429, "message": "Too Many Requests", "error": "Too Many Requests", "code": "too_many_requests"}),
731            ),
732            (
733                AppError::internal("db password=hunter2"),
734                json!({"statusCode": 500, "message": "Internal server error", "error": "Internal Server Error", "code": "internal_error"}),
735            ),
736            (
737                AppError::service_unavailable("Try again later."),
738                json!({"statusCode": 503, "message": "Try again later.", "error": "Service Unavailable", "code": "service_unavailable"}),
739            ),
740        ];
741        for (error, body) in cases {
742            assert!(
743                codes::ALL.contains(&error.code.as_str()),
744                "`{}` is in the table of stable codes",
745                error.code
746            );
747            assert_eq!(error.body(), body, "{error}");
748        }
749    }
750
751    #[test]
752    fn statuses_without_a_constructor_derive_their_code() {
753        let cases = [
754            (StatusCode::METHOD_NOT_ALLOWED, codes::METHOD_NOT_ALLOWED),
755            (
756                StatusCode::UNSUPPORTED_MEDIA_TYPE,
757                codes::UNSUPPORTED_MEDIA_TYPE,
758            ),
759            (StatusCode::PAYMENT_REQUIRED, "payment_required"),
760            (StatusCode::GONE, "gone"),
761        ];
762        for (status, code) in cases {
763            assert_eq!(AppError::from_status(status).code, code, "{status}");
764        }
765    }
766
767    #[test]
768    fn with_code_sets_the_rendered_code() {
769        let error = AppError::conflict("The campaign is already running.")
770            .with_code("campaign_already_running");
771        assert_eq!(error.status, StatusCode::CONFLICT);
772        assert_eq!(error.code, "campaign_already_running");
773        assert_eq!(
774            error.body(),
775            serde_json::json!({
776                "statusCode": 409,
777                "message": "The campaign is already running.",
778                "error": "Conflict",
779                "code": "campaign_already_running",
780            })
781        );
782    }
783
784    #[test]
785    fn code_comes_after_error_and_before_errors() {
786        let errors = BTreeMap::from([("name".to_owned(), vec!["name is required".to_owned()])]);
787        let response = AppError::validation(errors).render(ErrorFormat::default());
788        let text = futures_util::FutureExt::now_or_never(http_body_util::BodyExt::collect(
789            response.into_body(),
790        ))
791        .expect("a full body")
792        .expect("collects")
793        .to_bytes();
794        let text = String::from_utf8_lossy(&text);
795        let positions: Vec<usize> = [
796            "\"statusCode\"",
797            "\"message\"",
798            "\"error\"",
799            "\"code\"",
800            "\"errors\"",
801        ]
802        .iter()
803        .map(|key| text.find(key).expect(key))
804        .collect();
805        assert!(positions.is_sorted(), "member order: {text}");
806    }
807
808    #[test]
809    fn the_code_is_left_out_when_turned_off_or_empty() {
810        let off = ErrorFormat { code: false };
811        let body = AppError::not_found().body_as(off);
812        assert_eq!(
813            body,
814            serde_json::json!({"statusCode": 404, "message": "Not Found", "error": "Not Found"})
815        );
816        let empty = AppError::new(StatusCode::IM_A_TEAPOT, "", "Short and stout");
817        assert!(empty.body().get("code").is_none(), "{}", empty.body());
818    }
819
820    #[test]
821    fn statuses_have_codes_and_titles() {
822        assert_eq!(AppError::unauthenticated().status, StatusCode::UNAUTHORIZED);
823        assert_eq!(AppError::unauthenticated().title, "Unauthorized");
824        assert_eq!(AppError::forbidden().code, "forbidden");
825        assert_eq!(AppError::forbidden().title, "Forbidden");
826        assert_eq!(
827            AppError::from_status(StatusCode::TOO_MANY_REQUESTS).title,
828            "Too Many Requests"
829        );
830        let teapot = AppError::from_status(StatusCode::IM_A_TEAPOT);
831        assert_eq!(teapot.code, "i_m_a_teapot");
832        assert_eq!(teapot.title, "I'm a teapot");
833    }
834
835    #[test]
836    fn csrf_mismatch_is_403_invalid_csrf_token() {
837        let error = AppError::csrf_mismatch();
838        assert_eq!(error.status, StatusCode::FORBIDDEN);
839        assert_eq!(error.code, "csrf_token_mismatch");
840        assert_eq!(
841            error.body(),
842            serde_json::json!({
843                "statusCode": 403,
844                "message": "Invalid CSRF token",
845                "error": "Forbidden",
846                "code": "csrf_token_mismatch",
847            })
848        );
849    }
850
851    #[test]
852    fn body_uses_detail_as_message_and_reason_phrase_as_error() {
853        assert_eq!(
854            AppError::not_found().body(),
855            serde_json::json!({"statusCode": 404, "message": "Not Found", "error": "Not Found", "code": "not_found"})
856        );
857        assert_eq!(
858            AppError::conflict("Email taken").body(),
859            serde_json::json!({"statusCode": 409, "message": "Email taken", "error": "Conflict", "code": "conflict"})
860        );
861        let custom = AppError::new(
862            StatusCode::UNAUTHORIZED,
863            "invalid_signature",
864            "Invalid signature.",
865        );
866        assert_eq!(
867            custom.body(),
868            serde_json::json!({
869                "statusCode": 401,
870                "message": "Invalid signature.",
871                "error": "Unauthorized",
872                "code": "invalid_signature",
873            })
874        );
875        let odd = AppError::from_status(StatusCode::from_u16(599).unwrap());
876        assert_eq!(odd.body()["error"], "Error", "no reason phrase");
877    }
878
879    #[test]
880    fn validation_is_400_with_flattened_messages_in_field_order() {
881        let errors = BTreeMap::from([
882            (
883                "name".to_owned(),
884                vec!["name should not be empty".to_owned()],
885            ),
886            (
887                "email".to_owned(),
888                vec![
889                    "email must be a valid email address".to_owned(),
890                    "email must be shorter than or equal to 255 characters".to_owned(),
891                ],
892            ),
893        ]);
894        let error = AppError::validation(errors.clone()).with_detail("ignored when rendering");
895        assert_eq!(error.status, StatusCode::BAD_REQUEST);
896        assert_eq!(error.code, "validation_failed");
897        assert_eq!(
898            error.body(),
899            serde_json::json!({
900                "statusCode": 400,
901                "message": [
902                    "email must be a valid email address",
903                    "email must be shorter than or equal to 255 characters",
904                    "name should not be empty",
905                ],
906                "error": "Bad Request",
907                "code": "validation_failed",
908                "errors": errors,
909            })
910        );
911        let empty = AppError::validation(BTreeMap::new());
912        assert_eq!(empty.body()["message"], "Bad Request");
913        assert_eq!(empty.body()["errors"], serde_json::json!({}));
914    }
915
916    #[test]
917    fn rendered_errors_are_application_json() {
918        let response = AppError::not_found().render(ErrorFormat::default());
919        assert_eq!(response.status(), StatusCode::NOT_FOUND);
920        assert_eq!(response.headers()[CONTENT_TYPE], ERROR_CONTENT_TYPE);
921        assert_eq!(ERROR_CONTENT_TYPE, "application/json");
922    }
923
924    #[test]
925    fn too_many_requests_rounds_retry_after_up() {
926        let error = AppError::too_many_requests(Duration::from_millis(1500));
927        assert_eq!(error.headers[RETRY_AFTER], "2");
928        let error = AppError::too_many_requests(Duration::ZERO);
929        assert_eq!(error.headers[RETRY_AFTER], "1");
930    }
931
932    #[test]
933    fn internal_keeps_source_but_renders_no_detail() {
934        let error = AppError::internal(std::io::Error::other("db password=hunter2"));
935        assert_eq!(
936            error.body(),
937            serde_json::json!({
938                "statusCode": 500,
939                "message": "Internal server error",
940                "error": "Internal Server Error",
941                "code": "internal_error",
942            })
943        );
944        assert!(error.log_chain().contains("hunter2"), "logged, not sent");
945    }
946
947    #[test]
948    fn take_from_returns_the_error_a_response_carries_once() {
949        let mut response = AppError::conflict("Taken").into_response();
950        let error = AppError::take_from(&mut response).expect("the pending error");
951        assert_eq!(error.status, StatusCode::CONFLICT);
952        assert_eq!(error.detail.as_deref(), Some("Taken"));
953        assert!(AppError::take_from(&mut response).is_none(), "taken once");
954        let mut plain = (StatusCode::OK, "fine").into_response();
955        assert!(AppError::take_from(&mut plain).is_none());
956    }
957
958    #[test]
959    fn mappers_apply_to_the_source_chain() {
960        #[derive(Debug)]
961        struct Missing;
962        impl fmt::Display for Missing {
963            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
964                f.write_str("missing")
965            }
966        }
967        impl StdError for Missing {}
968        let mappers = [ErrorMapper::new::<Missing>(|_| Some(AppError::not_found()))];
969        let mapped = ErrorMapper::apply(&mappers, &AppError::internal(Missing)).expect("mapped");
970        assert_eq!(mapped.status, StatusCode::NOT_FOUND);
971        assert!(ErrorMapper::apply(&mappers, &AppError::internal("other")).is_none());
972        assert!(ErrorMapper::apply(&[], &AppError::internal(Missing)).is_none());
973    }
974
975    #[test]
976    fn strings_convert_with_question_mark() {
977        fn fails() -> Result<()> {
978            Err("boom")?
979        }
980        let error = fails().unwrap_err();
981        assert_eq!(error.status, StatusCode::INTERNAL_SERVER_ERROR);
982        assert_eq!(error.source.unwrap().to_string(), "boom");
983    }
984}