Skip to main content

rustango_cms/api/
error.rs

1//! A machine-readable error body for the v2 API.
2//!
3//! Every failure used to be a bare `(StatusCode, &'static str)`, which
4//! axum renders as `text/plain`. On an API whose success path is JSON
5//! that is a trap: a client's `await res.json()` throws a `SyntaxError`
6//! on *every* failure, so the handler reports a parse problem instead of
7//! the 404 that actually happened. And two 404s were distinguishable
8//! only by their prose — `"page not found"` vs `"menu not found"` — so
9//! branching meant string-matching English.
10//!
11//! Errors now carry the same envelope as everything else:
12//!
13//! ```json
14//! { "error": { "code": "not_found", "message": "page not found" } }
15//! ```
16//!
17//! `code` is the stable part. `message` is for humans and may be
18//! reworded; clients branch on `code` and on the HTTP status.
19
20use axum::http::StatusCode;
21use axum::response::{IntoResponse, Response};
22use axum::Json;
23
24/// A stable, machine-readable error identifier.
25///
26/// Deliberately small. Each variant maps to exactly one status, so a
27/// client can branch on either and get the same answer.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum ErrorCode {
30    /// The resource does not exist, is not public, or the caller may not
31    /// know whether it exists. Always 404 — see the note below.
32    NotFound,
33    /// The request itself is malformed: a bad query value, a missing
34    /// required parameter.
35    BadRequest,
36    /// The caller is not authenticated and authentication would help.
37    Unauthenticated,
38    /// The caller is authenticated but not allowed.
39    Forbidden,
40    /// The caller must supply a page password (`password` restriction).
41    PasswordRequired,
42    /// The path exists but not with this verb. The API is read-only, so
43    /// this is what every write attempt gets.
44    MethodNotAllowed,
45    /// Something failed server-side. The detail is logged, not returned.
46    Internal,
47}
48
49impl ErrorCode {
50    #[must_use]
51    pub fn as_str(self) -> &'static str {
52        match self {
53            Self::NotFound => "not_found",
54            Self::BadRequest => "bad_request",
55            Self::Unauthenticated => "unauthenticated",
56            Self::Forbidden => "forbidden",
57            Self::PasswordRequired => "password_required",
58            Self::MethodNotAllowed => "method_not_allowed",
59            Self::Internal => "internal_error",
60        }
61    }
62
63    #[must_use]
64    pub fn status(self) -> StatusCode {
65        match self {
66            Self::NotFound => StatusCode::NOT_FOUND,
67            Self::BadRequest => StatusCode::BAD_REQUEST,
68            Self::Unauthenticated => StatusCode::UNAUTHORIZED,
69            Self::Forbidden | Self::PasswordRequired => StatusCode::FORBIDDEN,
70            Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
71            Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
72        }
73    }
74}
75
76/// One API failure, rendered as JSON.
77#[derive(Debug, Clone)]
78pub struct ApiError {
79    pub code: ErrorCode,
80    pub message: String,
81}
82
83impl ApiError {
84    #[must_use]
85    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
86        Self {
87            code,
88            message: message.into(),
89        }
90    }
91
92    /// Not found, with one message covering "absent", "not public" and
93    /// "you may not see it" — distinguishing them would turn the
94    /// endpoint into an existence oracle for gated content.
95    #[must_use]
96    pub fn not_found(what: &str) -> Self {
97        Self::new(ErrorCode::NotFound, format!("{what} not found"))
98    }
99
100    #[must_use]
101    pub fn bad_request(message: impl Into<String>) -> Self {
102        Self::new(ErrorCode::BadRequest, message)
103    }
104
105    /// Server-side failure. The caller gets no detail; the cause belongs
106    /// in the log, not the response.
107    #[must_use]
108    pub fn internal() -> Self {
109        Self::new(ErrorCode::Internal, "internal error")
110    }
111
112    #[must_use]
113    pub fn unauthenticated() -> Self {
114        Self::new(
115            ErrorCode::Unauthenticated,
116            "authentication required to view this page",
117        )
118    }
119
120    #[must_use]
121    pub fn forbidden() -> Self {
122        Self::new(ErrorCode::Forbidden, "you don't have access to this page")
123    }
124
125    #[must_use]
126    pub fn password_required() -> Self {
127        Self::new(
128            ErrorCode::PasswordRequired,
129            "this page is password-protected",
130        )
131    }
132}
133
134impl IntoResponse for ApiError {
135    fn into_response(self) -> Response {
136        (
137            self.code.status(),
138            Json(serde_json::json!({
139                "error": { "code": self.code.as_str(), "message": self.message }
140            })),
141        )
142            .into_response()
143    }
144}
145
146/// Give axum's bodiless `405` the JSON envelope the rest of the API uses.
147///
148/// The router registers `GET` (and one `POST`, for login), so any other
149/// verb is refused by axum's own `MethodRouter` — correctly, and with the
150/// `Allow` header RFC 9110 requires. But it refuses with an *empty* body,
151/// and `docs/api.md` promises every failure is JSON with a stable code. A
152/// client that does `res.json()` on a failure — the normal shape of a
153/// fetch wrapper — got a `SyntaxError` pointing at its own parser instead
154/// of a 405 pointing at its verb.
155///
156/// The message does not name the permitted verbs, and cannot: axum
157/// attaches `Allow` *outside* `Router::layer`, so this middleware never
158/// sees it. That is the right division anyway — `Allow` is where a client
159/// is supposed to look, it is per-route (`/pages/` allows `GET,HEAD`,
160/// `/auth/login` allows `POST`), and duplicating it into prose from here
161/// would mean re-deriving routing knowledge that would eventually lie.
162/// Inner headers are carried across so replacing the body never drops
163/// one.
164pub async fn method_not_allowed_json(
165    req: axum::extract::Request,
166    next: axum::middleware::Next,
167) -> Response {
168    let resp = next.run(req).await;
169    if resp.status() != StatusCode::METHOD_NOT_ALLOWED {
170        return resp;
171    }
172
173    let (parts, _) = resp.into_parts();
174    let mut out = ApiError::new(ErrorCode::MethodNotAllowed, "method not allowed").into_response();
175    for (name, value) in parts.headers {
176        let Some(name) = name else { continue };
177        // Ours describe the new body; theirs described the empty one.
178        if name == axum::http::header::CONTENT_LENGTH
179            || name == axum::http::header::CONTENT_TYPE
180        {
181            continue;
182        }
183        out.headers_mut().insert(name, value);
184    }
185    out
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    #[test]
193    fn each_code_maps_to_one_status() {
194        assert_eq!(ErrorCode::NotFound.status(), StatusCode::NOT_FOUND);
195        assert_eq!(ErrorCode::BadRequest.status(), StatusCode::BAD_REQUEST);
196        assert_eq!(ErrorCode::Unauthenticated.status(), StatusCode::UNAUTHORIZED);
197        assert_eq!(ErrorCode::Forbidden.status(), StatusCode::FORBIDDEN);
198        assert_eq!(ErrorCode::PasswordRequired.status(), StatusCode::FORBIDDEN);
199        assert_eq!(
200            ErrorCode::Internal.status(),
201            StatusCode::INTERNAL_SERVER_ERROR,
202        );
203    }
204
205    #[test]
206    fn codes_are_stable_snake_case_identifiers() {
207        // Clients branch on these; renaming one is a breaking change.
208        for (code, want) in [
209            (ErrorCode::NotFound, "not_found"),
210            (ErrorCode::BadRequest, "bad_request"),
211            (ErrorCode::Unauthenticated, "unauthenticated"),
212            (ErrorCode::Forbidden, "forbidden"),
213            (ErrorCode::PasswordRequired, "password_required"),
214            (ErrorCode::Internal, "internal_error"),
215            (ErrorCode::MethodNotAllowed, "method_not_allowed"),
216        ] {
217            assert_eq!(code.as_str(), want);
218        }
219    }
220
221    #[test]
222    fn not_found_reads_naturally_and_hides_the_reason() {
223        // "absent" and "gated" must produce the same body.
224        assert_eq!(ApiError::not_found("page").message, "page not found");
225        assert_eq!(ApiError::not_found("menu").message, "menu not found");
226    }
227}