Skip to main content

fusion_stack/
errors.rs

1//! Error codes, the [`ApiError`] handlers return, and the JSON:API error documents every error
2//! response becomes.
3
4use std::collections::HashMap;
5use std::fmt;
6use std::sync::LazyLock;
7
8use laravel::http::{Request, Response, StatusCode};
9use regex::Regex;
10use serde::{Deserialize, Serialize};
11use serde_json::{Map, Value, json};
12
13use crate::State;
14use crate::request_id;
15
16/// The media type of Fusion Stack error documents.
17pub const CONTENT_TYPE: &str = "application/vnd.api+json";
18
19#[derive(Deserialize)]
20struct Table {
21    codes: Vec<Entry>,
22    fallbacks: HashMap<String, String>,
23}
24
25#[derive(Deserialize)]
26struct Entry {
27    code: String,
28    status: u16,
29    title: String,
30    #[serde(default)]
31    description: String,
32}
33
34/// The shared error table, `spec/error-codes.json`, which every Fusion Stack server package sends.
35static TABLE: LazyLock<Table> = LazyLock::new(|| {
36    serde_json::from_str(include_str!("../resources/error-codes.json"))
37        .expect("resources/error-codes.json is valid")
38});
39
40/// A machine-readable error code with the HTTP status it is sent with and a short title. An
41/// application implements it for its own codes, such as `invoice_not_finalised`.
42pub trait ErrorCode: fmt::Debug + Send + Sync {
43    /// The code, such as `invalid_api_version`.
44    fn code(&self) -> &str;
45    /// The HTTP status the code is sent with.
46    fn status(&self) -> u16;
47    /// A short, human-readable summary that does not change between occurrences.
48    fn title(&self) -> &str;
49    /// What the code means, for the OpenAPI document. Empty leaves it at the title.
50    fn description(&self) -> &str {
51        ""
52    }
53}
54
55macro_rules! codes {
56    ($($variant:ident => $code:literal,)*) => {
57        /// The error codes Fusion Stack itself sends. Their statuses and titles come from the
58        /// shared error table, so both server packages send the same ones.
59        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60        #[non_exhaustive]
61        pub enum ApiErrorCode {
62            $(#[doc = concat!("`", $code, "`")] $variant,)*
63        }
64
65        impl ApiErrorCode {
66            /// Every code, in the order of the shared error table.
67            pub const ALL: &[Self] = &[$(Self::$variant,)*];
68
69            /// The code as it is sent, such as `invalid_api_version`.
70            #[must_use]
71            pub const fn as_str(self) -> &'static str {
72                match self {
73                    $(Self::$variant => $code,)*
74                }
75            }
76
77            fn from_code(code: &str) -> Option<Self> {
78                match code {
79                    $($code => Some(Self::$variant),)*
80                    _ => None,
81                }
82            }
83        }
84    };
85}
86
87codes! {
88    BadRequest => "bad_request",
89    Unauthenticated => "unauthenticated",
90    Forbidden => "forbidden",
91    InsufficientScope => "insufficient_scope",
92    NotFound => "not_found",
93    MethodNotAllowed => "method_not_allowed",
94    Conflict => "conflict",
95    ValidationFailed => "validation_failed",
96    RateLimited => "rate_limited",
97    InvalidApiVersion => "invalid_api_version",
98    ApiVersionRetired => "api_version_retired",
99    ApiVersionBrownout => "api_version_brownout",
100    EndpointUnavailableForVersion => "endpoint_unavailable_for_version",
101    InvalidInclude => "invalid_include",
102    InvalidFieldset => "invalid_fieldset",
103    InvalidFilter => "invalid_filter",
104    InvalidSort => "invalid_sort",
105    InvalidPage => "invalid_page",
106    InvalidIdempotencyKey => "invalid_idempotency_key",
107    IdempotencyKeyMismatch => "idempotency_key_mismatch",
108    IdempotencyInProgress => "idempotency_in_progress",
109    HttpError => "http_error",
110    ServerError => "server_error",
111    ServiceUnavailable => "service_unavailable",
112}
113
114impl ApiErrorCode {
115    fn entry(self) -> &'static Entry {
116        TABLE
117            .codes
118            .iter()
119            .find(|entry| entry.code == self.as_str())
120            .expect("every ApiErrorCode is in the shared error table")
121    }
122
123    /// The code for an HTTP error status that has no more specific code.
124    #[must_use]
125    pub fn for_status(status: u16) -> Self {
126        let fallbacks = &TABLE.fallbacks;
127        let code = fallbacks
128            .get(&status.to_string())
129            .or_else(|| (status >= 500).then(|| &fallbacks["server"]))
130            .unwrap_or(&fallbacks["default"]);
131        Self::from_code(code).expect("the shared error table's fallbacks are known codes")
132    }
133}
134
135impl ErrorCode for ApiErrorCode {
136    fn code(&self) -> &str {
137        self.as_str()
138    }
139
140    fn status(&self) -> u16 {
141        self.entry().status
142    }
143
144    fn title(&self) -> &str {
145        &self.entry().title
146    }
147
148    fn description(&self) -> &str {
149        &self.entry().description
150    }
151}
152
153impl fmt::Display for ApiErrorCode {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        f.write_str(self.as_str())
156    }
157}
158
159/// An error with a Fusion Stack error code, rendered as one JSON:API error object. Return it from
160/// a handler or middleware with `?` or `Err(..)?`; it converts into `laravel::Error`.
161///
162/// ```
163/// use fusion_stack::errors::{ApiError, ApiErrorCode};
164///
165/// let error = ApiError::new(ApiErrorCode::InvalidFilter, "Unknown filter [colour].")
166///     .parameter("filter[colour]");
167/// ```
168#[derive(Debug, Clone)]
169pub struct ApiError {
170    code: String,
171    status: u16,
172    title: String,
173    detail: String,
174    source: Map<String, Value>,
175    links: Map<String, Value>,
176    meta: Map<String, Value>,
177    pub(crate) headers: Vec<(String, String)>,
178}
179
180impl ApiError {
181    /// An error with the code's status and title.
182    pub fn new(code: impl ErrorCode, detail: impl Into<String>) -> Self {
183        Self {
184            code: code.code().to_owned(),
185            status: code.status(),
186            title: code.title().to_owned(),
187            detail: detail.into(),
188            source: Map::new(),
189            links: Map::new(),
190            meta: Map::new(),
191            headers: Vec::new(),
192        }
193    }
194
195    /// A `not_found` error for a record that does not exist, worded without naming the model.
196    #[must_use]
197    pub fn not_found() -> Self {
198        Self::new(
199            ApiErrorCode::NotFound,
200            "The requested resource could not be found.",
201        )
202    }
203
204    /// Points at the request document member at fault, as a JSON pointer such as `/data/attributes/email`.
205    #[must_use]
206    pub fn pointer(mut self, pointer: impl Into<String>) -> Self {
207        self.source
208            .insert("pointer".into(), Value::String(pointer.into()));
209        self
210    }
211
212    /// Names the query parameter at fault, such as `include`.
213    #[must_use]
214    pub fn parameter(mut self, parameter: impl Into<String>) -> Self {
215        self.source
216            .insert("parameter".into(), Value::String(parameter.into()));
217        self
218    }
219
220    /// Names the request header at fault, such as `Api-Version`.
221    #[must_use]
222    pub fn header_source(mut self, header: impl Into<String>) -> Self {
223        self.source
224            .insert("header".into(), Value::String(header.into()));
225        self
226    }
227
228    /// Adds a link, such as `about` to an upgrade guide.
229    #[must_use]
230    pub fn link(mut self, name: impl Into<String>, url: impl Into<String>) -> Self {
231        self.links.insert(name.into(), Value::String(url.into()));
232        self
233    }
234
235    /// Adds a `meta` member, such as `latest_version`.
236    #[must_use]
237    pub fn meta(mut self, key: impl Into<String>, value: impl Serialize) -> Self {
238        self.meta.insert(
239            key.into(),
240            serde_json::to_value(value).unwrap_or(Value::Null),
241        );
242        self
243    }
244
245    /// Adds a response header, such as `Retry-After`.
246    #[must_use]
247    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
248        self.headers.push((name.into(), value.into()));
249        self
250    }
251
252    /// The error's code, such as `invalid_api_version`.
253    #[must_use]
254    pub fn code(&self) -> &str {
255        &self.code
256    }
257
258    /// The HTTP status the error is sent with.
259    #[must_use]
260    pub const fn status(&self) -> u16 {
261        self.status
262    }
263
264    fn object(&self) -> Value {
265        error_object(
266            self.status,
267            &self.code,
268            &self.title,
269            &self.detail,
270            &self.source,
271            &self.links,
272            &self.meta,
273        )
274    }
275}
276
277impl fmt::Display for ApiError {
278    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279        f.write_str(&self.detail)
280    }
281}
282
283impl std::error::Error for ApiError {}
284
285impl ApiError {
286    /// The error as a `laravel::Error` with its status and headers, for `Err(error.into_error())`.
287    /// Laravel for Rust converts any error with `?`, but that conversion gives it a 500 status,
288    /// which the error handler then logs as a failure.
289    pub fn into_error(self) -> laravel::Error {
290        let headers = self.headers.clone();
291        let mut converted = laravel::Error::new(self.status, self);
292        for (name, value) in headers {
293            converted = converted.with_header(name, value);
294        }
295        converted
296    }
297}
298
299/// The hidden context value that carries a 405's methods from [`AllowHeader`] to the renderer.
300const ALLOWED: &str = "fusion_stack.allowed_methods";
301
302/// Writes `Allow` as Symfony, and so the PHP package, does (`GET, HEAD` rather than Laravel for
303/// Rust's `GET,HEAD`), and keeps its methods for the 405 error's detail. Global middleware, because
304/// the framework renders an unmatched method's error before it copies the `Allow` header over.
305pub(crate) struct AllowHeader;
306
307impl laravel::http::Middleware for AllowHeader {
308    async fn handle(
309        &self,
310        request: Request,
311        next: laravel::http::Next,
312    ) -> laravel::Result<Response> {
313        let mut response = next.run(request).await.into_http();
314        let allow = response
315            .headers()
316            .get(laravel::http::header::ALLOW)
317            .and_then(|value| value.to_str().ok())
318            .map(|allow| {
319                allow
320                    .split(',')
321                    .map(str::trim)
322                    .collect::<Vec<_>>()
323                    .join(", ")
324            });
325        if let Some(allow) = allow {
326            if let Ok(value) = allow.parse() {
327                response
328                    .headers_mut()
329                    .insert(laravel::http::header::ALLOW, value);
330            }
331            laravel::context::add_hidden(ALLOWED, allow);
332        }
333        Ok(Response::from_http(response))
334    }
335}
336
337/// One error object, with empty members left out, in the order the PHP package writes them.
338fn error_object(
339    status: u16,
340    code: &str,
341    title: &str,
342    detail: &str,
343    source: &Map<String, Value>,
344    links: &Map<String, Value>,
345    meta: &Map<String, Value>,
346) -> Value {
347    let mut object = Map::new();
348    object.insert("status".into(), json!(status.to_string()));
349    object.insert("code".into(), json!(code));
350    object.insert("title".into(), json!(title));
351    object.insert("detail".into(), json!(detail));
352    for (key, member) in [("source", source), ("links", links), ("meta", meta)] {
353        if !member.is_empty() {
354            object.insert(key.into(), Value::Object(member.clone()));
355        }
356    }
357    Value::Object(object)
358}
359
360fn reason(status: u16) -> &'static str {
361    StatusCode::from_u16(status)
362        .ok()
363        .and_then(|status| status.canonical_reason())
364        .unwrap_or("Error")
365}
366
367/// The title of a code sent with a status: `http_error` takes the status's reason phrase.
368fn title(code: ApiErrorCode, status: u16) -> String {
369    if code == ApiErrorCode::HttpError {
370        reason(status).to_owned()
371    } else {
372        code.title().to_owned()
373    }
374}
375
376/// Whether the request's path matches one of the patterns, where `*` matches anything.
377pub(crate) fn path_matches(patterns: &[String], path: &str) -> bool {
378    let path = path.trim_start_matches('/');
379    patterns
380        .iter()
381        .any(|pattern| crate::glob(pattern.trim_start_matches('/'), path))
382}
383
384/// Replaces an error response with a JSON:API error document. Registered with
385/// `errors.respond`, so it runs for every error the application renders.
386pub(crate) fn render(
387    state: &State,
388    response: Response,
389    error: &laravel::Error,
390    request: &Request,
391) -> Response {
392    if !path_matches(&state.config.error_paths, request.path()) {
393        return response;
394    }
395
396    let http = response.into_http();
397    let (mut parts, _) = http.into_parts();
398    // An ApiError converted with `?` instead of into_error() arrives as a 500: send its own status.
399    if let Some(error) = error.downcast_ref::<ApiError>()
400        && let Ok(status) = StatusCode::from_u16(error.status)
401    {
402        parts.status = status;
403    }
404    let status = parts.status.as_u16();
405
406    let mut errors = objects(error, request, status);
407    let id = request_id::of(request);
408    if state.config.request_ids {
409        for object in &mut errors {
410            if let Some(object) = object.as_object_mut() {
411                let meta = object.entry("meta").or_insert_with(|| json!({}));
412                if let Some(meta) = meta.as_object_mut() {
413                    meta.insert("request_id".into(), json!(id));
414                }
415            }
416        }
417    }
418
419    let headers = &mut parts.headers;
420    headers.remove(laravel::http::header::CONTENT_LENGTH);
421    headers.insert(
422        laravel::http::header::CONTENT_TYPE,
423        CONTENT_TYPE.parse().expect("a valid header value"),
424    );
425    if state.config.request_ids
426        && let Ok(value) = id.parse()
427    {
428        headers.insert(request_id::HEADER, value);
429    }
430
431    let body = serde_json::to_vec(&json!({ "errors": errors })).expect("error documents serialize");
432    Response::from_http(laravel::axum::http::Response::from_parts(
433        parts,
434        body.into(),
435    ))
436}
437
438fn objects(error: &laravel::Error, request: &Request, status: u16) -> Vec<Value> {
439    if let Some(error) = error.downcast_ref::<ApiError>() {
440        return vec![error.object()];
441    }
442
443    if let Some(invalid) = error.downcast_ref::<laravel::validation::InvalidInput>() {
444        return validation_errors(invalid, request, status);
445    }
446
447    #[cfg(feature = "database")]
448    if error.is::<laravel::model::ModelNotFound>() {
449        return vec![ApiError::not_found().object()];
450    }
451
452    let code = ApiErrorCode::for_status(status);
453    let path = request.path().trim_start_matches('/');
454    let detail = if status >= 500 {
455        "An unexpected error occurred.".to_owned()
456    } else if request.current_route().is_none() && status == 404 {
457        format!("The route {path} could not be found.")
458    } else if request.current_route().is_none() && status == 405 {
459        format!(
460            "The {} method is not supported for route {path}. Supported methods: {}.",
461            request.method(),
462            laravel::context::get_hidden::<String>(ALLOWED).unwrap_or_default()
463        )
464    } else {
465        let message = error.to_string();
466        if message.is_empty() || message == reason(status) {
467            title(code, status)
468        } else {
469            message
470        }
471    };
472
473    vec![error_object(
474        status,
475        code.as_str(),
476        &title(code, status),
477        &detail,
478        &Map::new(),
479        &Map::new(),
480        &Map::new(),
481    )]
482}
483
484fn validation_errors(
485    invalid: &laravel::validation::InvalidInput,
486    request: &Request,
487    status: u16,
488) -> Vec<Value> {
489    let code = ApiErrorCode::ValidationFailed;
490    let mut errors = Vec::new();
491    for (field, messages) in invalid.errors() {
492        let source = source(field, request);
493        for message in messages {
494            let detail = without_field_name(message, field);
495            errors.push(error_object(
496                status,
497                code.as_str(),
498                &title(code, status),
499                &detail,
500                &source,
501                &Map::new(),
502                &Map::new(),
503            ));
504        }
505    }
506    errors
507}
508
509/// Replaces the field's name in a validation message with "this field", so "The email field is
510/// required." becomes "This field is required.". The pointer says which field; the message must not
511/// name it, because the name differs between API versions.
512fn without_field_name(message: &str, field: &str) -> String {
513    let last = field.rsplit('.').next().unwrap_or(field);
514    let mut names = vec![
515        field.to_owned(),
516        field.replace('_', " "),
517        last.to_owned(),
518        last.replace('_', " "),
519    ];
520    names.dedup();
521    for name in names {
522        let pattern = format!(
523            r"(?i)\b(the)(?: selected)? {}(?: field)?\b",
524            regex::escape(&name)
525        );
526        let Ok(regex) = Regex::new(&pattern) else {
527            continue;
528        };
529        if regex.is_match(message) {
530            return regex
531                .replace_all(message, |captures: &regex::Captures<'_>| {
532                    if captures[1].starts_with('T') {
533                        "This field"
534                    } else {
535                        "this field"
536                    }
537                })
538                .into_owned();
539        }
540    }
541    message.to_owned()
542}
543
544/// The query parameter or request document member a validated field came from. In a JSON:API
545/// document a bare field name refers to an attribute.
546fn source(field: &str, request: &Request) -> Map<String, Value> {
547    let mut segments: Vec<&str> = field.split('.').collect();
548    let mut source = Map::new();
549
550    let in_query = request.uri().query().is_some_and(|query| {
551        query.split('&').any(|pair| {
552            let key = pair.split('=').next().unwrap_or_default();
553            key == segments[0]
554                || key.starts_with(&format!("{}[", segments[0]))
555                || key.starts_with(&format!("{}%5B", segments[0]))
556        })
557    });
558    if in_query {
559        let first = segments.remove(0);
560        let rest: String = segments
561            .iter()
562            .map(|segment| format!("[{segment}]"))
563            .collect();
564        source.insert("parameter".into(), json!(format!("{first}{rest}")));
565        return source;
566    }
567
568    let json_api = request
569        .header(laravel::http::header::CONTENT_TYPE)
570        .is_some_and(|value| value.contains(CONTENT_TYPE));
571    if segments[0] != "data" && json_api {
572        segments.splice(0..0, ["data", "attributes"]);
573    }
574    let pointer: String = segments
575        .iter()
576        .map(|segment| format!("/{}", segment.replace('~', "~0").replace('/', "~1")))
577        .collect();
578    source.insert("pointer".into(), json!(pointer));
579    source
580}
581
582#[cfg(test)]
583mod tests {
584    use super::*;
585
586    #[test]
587    fn every_code_in_the_shared_table_is_an_api_error_code() {
588        let codes: Vec<&str> = TABLE
589            .codes
590            .iter()
591            .map(|entry| entry.code.as_str())
592            .collect();
593        let variants: Vec<&str> = ApiErrorCode::ALL.iter().map(|code| code.as_str()).collect();
594        assert_eq!(codes, variants);
595    }
596
597    #[test]
598    fn statuses_without_their_own_code_fall_back_like_the_php_package() {
599        // Expected values from ApiErrorCode::forStatus() in the PHP package.
600        let cases = [
601            (400, "bad_request"),
602            (401, "unauthenticated"),
603            (403, "forbidden"),
604            (404, "not_found"),
605            (405, "method_not_allowed"),
606            (409, "conflict"),
607            (410, "http_error"),
608            (418, "http_error"),
609            (422, "validation_failed"),
610            (429, "rate_limited"),
611            (500, "server_error"),
612            (502, "server_error"),
613            (503, "service_unavailable"),
614        ];
615        for (status, code) in cases {
616            assert_eq!(
617                ApiErrorCode::for_status(status).as_str(),
618                code,
619                "status {status}"
620            );
621        }
622    }
623
624    #[test]
625    fn statuses_and_titles_come_from_the_table() {
626        assert_eq!(ApiErrorCode::IdempotencyKeyMismatch.status(), 422);
627        assert_eq!(
628            ApiErrorCode::IdempotencyKeyMismatch.title(),
629            "Idempotency key reused"
630        );
631        assert_eq!(title(ApiErrorCode::HttpError, 418), "I'm a teapot");
632    }
633
634    #[test]
635    fn validation_messages_stop_naming_the_field() {
636        assert_eq!(
637            without_field_name("The email field must be a valid email address.", "email"),
638            "This field must be a valid email address."
639        );
640        assert_eq!(
641            without_field_name("The selected status is invalid.", "data.attributes.status"),
642            "This field is invalid."
643        );
644        assert_eq!(
645            without_field_name("The full name field is required.", "full_name"),
646            "This field is required."
647        );
648        // "email" elsewhere in the message is not the field's name.
649        assert_eq!(
650            without_field_name("Enter a valid email address.", "email"),
651            "Enter a valid email address."
652        );
653    }
654}