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    /// Too many attempts; retry after the `Retry-After` header.
46    RateLimited,
47    /// Busy for a moment; retry after the `Retry-After` header.
48    Unavailable,
49    /// Something failed server-side. The detail is logged, not returned.
50    Internal,
51}
52
53impl ErrorCode {
54    #[must_use]
55    pub fn as_str(self) -> &'static str {
56        match self {
57            Self::NotFound => "not_found",
58            Self::BadRequest => "bad_request",
59            Self::Unauthenticated => "unauthenticated",
60            Self::Forbidden => "forbidden",
61            Self::PasswordRequired => "password_required",
62            Self::MethodNotAllowed => "method_not_allowed",
63            Self::RateLimited => "rate_limited",
64            Self::Unavailable => "unavailable",
65            Self::Internal => "internal_error",
66        }
67    }
68
69    #[must_use]
70    pub fn status(self) -> StatusCode {
71        match self {
72            Self::NotFound => StatusCode::NOT_FOUND,
73            Self::BadRequest => StatusCode::BAD_REQUEST,
74            Self::Unauthenticated => StatusCode::UNAUTHORIZED,
75            Self::Forbidden | Self::PasswordRequired => StatusCode::FORBIDDEN,
76            Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
77            Self::RateLimited => StatusCode::TOO_MANY_REQUESTS,
78            Self::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
79            Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
80        }
81    }
82}
83
84/// One API failure, rendered as JSON.
85#[derive(Debug, Clone)]
86pub struct ApiError {
87    pub code: ErrorCode,
88    pub message: String,
89}
90
91impl ApiError {
92    #[must_use]
93    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
94        Self {
95            code,
96            message: message.into(),
97        }
98    }
99
100    /// Not found, with one message covering "absent", "not public" and
101    /// "you may not see it" — distinguishing them would turn the
102    /// endpoint into an existence oracle for gated content.
103    #[must_use]
104    pub fn not_found(what: &str) -> Self {
105        Self::new(ErrorCode::NotFound, format!("{what} not found"))
106    }
107
108    #[must_use]
109    pub fn bad_request(message: impl Into<String>) -> Self {
110        Self::new(ErrorCode::BadRequest, message)
111    }
112
113    /// Server-side failure. The caller gets no detail; the cause belongs
114    /// in the log, not the response.
115    #[must_use]
116    pub fn internal() -> Self {
117        Self::new(ErrorCode::Internal, "internal error")
118    }
119
120    #[must_use]
121    pub fn unauthenticated() -> Self {
122        Self::new(
123            ErrorCode::Unauthenticated,
124            "authentication required to view this page",
125        )
126    }
127
128    #[must_use]
129    pub fn forbidden() -> Self {
130        Self::new(ErrorCode::Forbidden, "you don't have access to this page")
131    }
132
133    #[must_use]
134    pub fn password_required() -> Self {
135        Self::new(
136            ErrorCode::PasswordRequired,
137            "this page is password-protected",
138        )
139    }
140}
141
142impl IntoResponse for ApiError {
143    fn into_response(self) -> Response {
144        (
145            self.code.status(),
146            Json(serde_json::json!({
147                "error": { "code": self.code.as_str(), "message": self.message }
148            })),
149        )
150            .into_response()
151    }
152}
153
154/// Give axum's bodiless `405` the JSON envelope the rest of the API uses.
155///
156/// The router registers `GET` (and one `POST`, for login), so any other
157/// verb is refused by axum's own `MethodRouter` — correctly, and with the
158/// `Allow` header RFC 9110 requires. But it refuses with an *empty* body,
159/// and `docs/api.md` promises every failure is JSON with a stable code. A
160/// client that does `res.json()` on a failure — the normal shape of a
161/// fetch wrapper — got a `SyntaxError` pointing at its own parser instead
162/// of a 405 pointing at its verb.
163///
164/// The message does not name the permitted verbs, and cannot: axum
165/// attaches `Allow` *outside* `Router::layer`, so this middleware never
166/// sees it. That is the right division anyway — `Allow` is where a client
167/// is supposed to look, it is per-route (`/pages/` allows `GET,HEAD`,
168/// `/auth/login` allows `POST`), and duplicating it into prose from here
169/// would mean re-deriving routing knowledge that would eventually lie.
170/// Inner headers are carried across so replacing the body never drops
171/// one.
172pub async fn method_not_allowed_json(
173    req: axum::extract::Request,
174    next: axum::middleware::Next,
175) -> Response {
176    let resp = next.run(req).await;
177    if resp.status() != StatusCode::METHOD_NOT_ALLOWED {
178        return resp;
179    }
180
181    let (parts, _) = resp.into_parts();
182    let mut out = ApiError::new(ErrorCode::MethodNotAllowed, "method not allowed").into_response();
183    for (name, value) in parts.headers {
184        let Some(name) = name else { continue };
185        // Ours describe the new body; theirs described the empty one.
186        if name == axum::http::header::CONTENT_LENGTH
187            || name == axum::http::header::CONTENT_TYPE
188        {
189            continue;
190        }
191        out.headers_mut().insert(name, value);
192    }
193    out
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199
200    #[test]
201    fn each_code_maps_to_one_status() {
202        assert_eq!(ErrorCode::NotFound.status(), StatusCode::NOT_FOUND);
203        assert_eq!(ErrorCode::BadRequest.status(), StatusCode::BAD_REQUEST);
204        assert_eq!(ErrorCode::Unauthenticated.status(), StatusCode::UNAUTHORIZED);
205        assert_eq!(ErrorCode::Forbidden.status(), StatusCode::FORBIDDEN);
206        assert_eq!(ErrorCode::PasswordRequired.status(), StatusCode::FORBIDDEN);
207        assert_eq!(ErrorCode::RateLimited.status(), StatusCode::TOO_MANY_REQUESTS);
208        assert_eq!(ErrorCode::Unavailable.status(), StatusCode::SERVICE_UNAVAILABLE);
209        assert_eq!(
210            ErrorCode::Internal.status(),
211            StatusCode::INTERNAL_SERVER_ERROR,
212        );
213    }
214
215    #[test]
216    fn codes_are_stable_snake_case_identifiers() {
217        // Clients branch on these; renaming one is a breaking change.
218        for (code, want) in [
219            (ErrorCode::NotFound, "not_found"),
220            (ErrorCode::BadRequest, "bad_request"),
221            (ErrorCode::Unauthenticated, "unauthenticated"),
222            (ErrorCode::Forbidden, "forbidden"),
223            (ErrorCode::PasswordRequired, "password_required"),
224            (ErrorCode::Internal, "internal_error"),
225            (ErrorCode::MethodNotAllowed, "method_not_allowed"),
226            (ErrorCode::RateLimited, "rate_limited"),
227            (ErrorCode::Unavailable, "unavailable"),
228        ] {
229            assert_eq!(code.as_str(), want);
230        }
231    }
232
233    #[test]
234    fn not_found_reads_naturally_and_hides_the_reason() {
235        // "absent" and "gated" must produce the same body.
236        assert_eq!(ApiError::not_found("page").message, "page not found");
237        assert_eq!(ApiError::not_found("menu").message, "menu not found");
238    }
239}