Skip to main content

web/
error_render.rs

1use askama::Template;
2use axum::{
3    body::{Body, to_bytes},
4    http::{HeaderMap, HeaderName, HeaderValue, Request, StatusCode, header},
5    middleware::Next,
6    response::{Html, IntoResponse, Redirect, Response},
7};
8
9use crate::response::WebError;
10
11#[derive(Template)]
12#[template(
13    source = r#"<div class="error-alert">{{ message }}</div>"#,
14    ext = "html"
15)]
16struct ErrorFragment<'a> {
17    message: &'a str,
18}
19
20#[derive(Template)]
21#[template(path = "pages/error.html")]
22struct ErrorPage<'a> {
23    status: u16,
24    message: &'a str,
25    back: &'a str,
26}
27
28enum Format {
29    Fragment,
30    Page { back: String },
31    Json,
32}
33
34impl Format {
35    fn of(headers: &HeaderMap) -> Self {
36        if header_str(headers, "hx-request") == Some("true") {
37            return Self::Fragment;
38        }
39        match header_str(headers, header::ACCEPT.as_str()) {
40            Some(accept) if accept.contains("text/html") => Self::Page {
41                back: back_link(headers),
42            },
43            _ => Self::Json,
44        }
45    }
46}
47
48fn header_str<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
49    headers.get(name).and_then(|v| v.to_str().ok())
50}
51
52/// The Referer's path when it points at this host, else the root.
53fn back_link(headers: &HeaderMap) -> String {
54    let same_origin = header_str(headers, header::REFERER.as_str())
55        .and_then(|referer| referer.split_once("://"))
56        .and_then(|(_, rest)| rest.split_once('/').or(Some((rest, ""))))
57        .filter(|(host, _)| header_str(headers, header::HOST.as_str()) == Some(host));
58    match same_origin {
59        Some((_, path)) => format!("/{}", path.trim_start_matches(['/', '\\'])),
60        None => "/".to_string(),
61    }
62}
63
64/// Marks the response of a page route: its failure renders as a page
65/// whatever the request accepts.
66#[derive(Clone, Copy)]
67struct FullPage;
68
69/// Route layer of the page routers: a browser navigation never shows a
70/// failure as raw JSON.
71pub async fn full_page(req: Request<Body>, next: Next) -> Response {
72    let mut response = next.run(req).await;
73    response.extensions_mut().insert(FullPage);
74    response
75}
76
77const LOGIN: &str = "/login";
78const REJECTION_BODY_LIMIT: usize = 1024;
79const REJECTION_MESSAGE_CHARS: usize = 200;
80const REPRESENTATION_HEADERS: [HeaderName; 5] = [
81    header::CONTENT_TYPE,
82    header::CONTENT_LENGTH,
83    header::CONTENT_ENCODING,
84    header::ETAG,
85    header::LAST_MODIFIED,
86];
87
88/// Keeps the headers of the replaced response (rotated session cookies above all);
89/// only those describing the old body and ones the replacement already set are dropped.
90fn carry_headers(from: &HeaderMap, to: &mut Response) {
91    for name in from.keys() {
92        if REPRESENTATION_HEADERS.contains(name) || to.headers().contains_key(name) {
93            continue;
94        }
95        for value in from.get_all(name) {
96            to.headers_mut().append(name.clone(), value.clone());
97        }
98    }
99}
100
101fn html_response(error: &WebError, rendered: askama::Result<String>) -> Option<Response> {
102    let html = rendered.ok()?;
103    let mut response = (error.status, Html(html)).into_response();
104    response.headers_mut().insert(
105        header::CONTENT_TYPE,
106        HeaderValue::from_static("text/html; charset=utf-8"),
107    );
108    Some(response)
109}
110
111/// Not logged in is not an error to display: the client is sent to log in.
112/// htmx performs `HX-Redirect` whatever the status, so the 401 is kept.
113fn login_redirect(format: Format) -> Option<Response> {
114    match format {
115        Format::Page { .. } => Some(Redirect::to(LOGIN).into_response()),
116        Format::Fragment => Some(
117            (
118                StatusCode::UNAUTHORIZED,
119                [("HX-Redirect", HeaderValue::from_static(LOGIN))],
120            )
121                .into_response(),
122        ),
123        Format::Json => None,
124    }
125}
126
127fn render(error: &WebError, format: Format) -> Option<Response> {
128    if error.status == StatusCode::UNAUTHORIZED {
129        return login_redirect(format);
130    }
131    let rendered = match format {
132        Format::Fragment => ErrorFragment {
133            message: &error.message,
134        }
135        .render(),
136        Format::Page { back } => ErrorPage {
137            status: error.status.as_u16(),
138            message: &error.message,
139            back: &back,
140        }
141        .render(),
142        Format::Json => return None,
143    };
144    html_response(error, rendered)
145}
146
147fn is_plain_text_failure(response: &Response) -> bool {
148    response.status().as_u16() >= 400
149        && response.extensions().get::<WebError>().is_none()
150        && header_str(response.headers(), header::CONTENT_TYPE.as_str())
151            .is_some_and(|content_type| content_type.starts_with("text/plain"))
152}
153
154async fn rejection_message(status: StatusCode, body: Body) -> String {
155    let text = match to_bytes(body, REJECTION_BODY_LIMIT).await {
156        Ok(bytes) => String::from_utf8_lossy(&bytes).trim().to_string(),
157        Err(_) => String::new(),
158    };
159    match text.is_empty() {
160        true => status.canonical_reason().unwrap_or("Error").to_string(),
161        false => text.chars().take(REJECTION_MESSAGE_CHARS).collect(),
162    }
163}
164
165/// Extractor rejections answer plain text; turned into a `WebError` they render like every other failure.
166pub async fn adopt_rejection(response: Response) -> Response {
167    if !is_plain_text_failure(&response) {
168        return response;
169    }
170    let (parts, body) = response.into_parts();
171    let message = rejection_message(parts.status, body).await;
172    let mut adopted = WebError::new(parts.status, message).into_response();
173    carry_headers(&parts.headers, &mut adopted);
174    adopted
175}
176
177/// Re-renders a `WebError` response as an htmx fragment, an error page or JSON, by request;
178/// a page route's failure is never JSON, and a 401 becomes a redirect to the login page.
179pub async fn render_web_error(req: Request<Body>, next: Next) -> Response {
180    let format = Format::of(req.headers());
181    let page = Format::Page {
182        back: back_link(req.headers()),
183    };
184    let response = next.run(req).await;
185    let format = match (format, response.extensions().get::<FullPage>()) {
186        (Format::Json, Some(_)) => page,
187        (format, _) => format,
188    };
189    let response = adopt_rejection(response).await;
190    let Some(error) = response.extensions().get::<WebError>().cloned() else {
191        return response;
192    };
193    match render(&error, format) {
194        Some(mut rendered) => {
195            carry_headers(response.headers(), &mut rendered);
196            rendered
197        }
198        None => response,
199    }
200}
201
202#[cfg(test)]
203#[path = "error_render_tests.rs"]
204mod tests;