1
use askama::Template;
2
use 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

            
9
use crate::response::WebError;
10

            
11
#[derive(Template)]
12
#[template(
13
    source = r#"<div class="error-alert">{{ message }}</div>"#,
14
    ext = "html"
15
)]
16
struct ErrorFragment<'a> {
17
    message: &'a str,
18
}
19

            
20
#[derive(Template)]
21
#[template(path = "pages/error.html")]
22
struct ErrorPage<'a> {
23
    status: u16,
24
    message: &'a str,
25
    back: &'a str,
26
}
27

            
28
enum Format {
29
    Fragment,
30
    Page { back: String },
31
    Json,
32
}
33

            
34
impl Format {
35
542
    fn of(headers: &HeaderMap) -> Self {
36
542
        if header_str(headers, "hx-request") == Some("true") {
37
218
            return Self::Fragment;
38
324
        }
39
324
        match header_str(headers, header::ACCEPT.as_str()) {
40
79
            Some(accept) if accept.contains("text/html") => Self::Page {
41
25
                back: back_link(headers),
42
25
            },
43
299
            _ => Self::Json,
44
        }
45
542
    }
46
}
47

            
48
1561
fn header_str<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
49
1561
    headers.get(name).and_then(|v| v.to_str().ok())
50
1561
}
51

            
52
/// The Referer's path when it points at this host, else the root.
53
567
fn back_link(headers: &HeaderMap) -> String {
54
567
    let same_origin = header_str(headers, header::REFERER.as_str())
55
16
        .and_then(|referer| referer.split_once("://"))
56
16
        .and_then(|(_, rest)| rest.split_once('/').or(Some((rest, ""))))
57
16
        .filter(|(host, _)| header_str(headers, header::HOST.as_str()) == Some(host));
58
567
    match same_origin {
59
12
        Some((_, path)) => format!("/{}", path.trim_start_matches(['/', '\\'])),
60
555
        None => "/".to_string(),
61
    }
62
567
}
63

            
64
/// Marks the response of a page route: its failure renders as a page
65
/// whatever the request accepts.
66
#[derive(Clone, Copy)]
67
struct FullPage;
68

            
69
/// Route layer of the page routers: a browser navigation never shows a
70
/// failure as raw JSON.
71
105
pub async fn full_page(req: Request<Body>, next: Next) -> Response {
72
105
    let mut response = next.run(req).await;
73
105
    response.extensions_mut().insert(FullPage);
74
105
    response
75
105
}
76

            
77
const LOGIN: &str = "/login";
78
const REJECTION_BODY_LIMIT: usize = 1024;
79
const REJECTION_MESSAGE_CHARS: usize = 200;
80
const 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.
90
96
fn carry_headers(from: &HeaderMap, to: &mut Response) {
91
96
    for name in from.keys() {
92
144
        if REPRESENTATION_HEADERS.contains(name) || to.headers().contains_key(name) {
93
96
            continue;
94
48
        }
95
48
        for value in from.get_all(name) {
96
96
            to.headers_mut().append(name.clone(), value.clone());
97
        }
98
    }
99
96
}
100

            
101
73
fn html_response(error: &WebError, rendered: askama::Result<String>) -> Option<Response> {
102
73
    let html = rendered.ok()?;
103
73
    let mut response = (error.status, Html(html)).into_response();
104
73
    response.headers_mut().insert(
105
73
        header::CONTENT_TYPE,
106
73
        HeaderValue::from_static("text/html; charset=utf-8"),
107
73
    );
108
73
    Some(response)
109
73
}
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.
113
15
fn login_redirect(format: Format) -> Option<Response> {
114
15
    match format {
115
10
        Format::Page { .. } => Some(Redirect::to(LOGIN).into_response()),
116
3
        Format::Fragment => Some(
117
3
            (
118
3
                StatusCode::UNAUTHORIZED,
119
3
                [("HX-Redirect", HeaderValue::from_static(LOGIN))],
120
3
            )
121
3
                .into_response(),
122
3
        ),
123
2
        Format::Json => None,
124
    }
125
15
}
126

            
127
142
fn render(error: &WebError, format: Format) -> Option<Response> {
128
142
    if error.status == StatusCode::UNAUTHORIZED {
129
15
        return login_redirect(format);
130
127
    }
131
127
    let rendered = match format {
132
26
        Format::Fragment => ErrorFragment {
133
26
            message: &error.message,
134
26
        }
135
26
        .render(),
136
47
        Format::Page { back } => ErrorPage {
137
47
            status: error.status.as_u16(),
138
47
            message: &error.message,
139
47
            back: &back,
140
47
        }
141
47
        .render(),
142
54
        Format::Json => return None,
143
    };
144
73
    html_response(error, rendered)
145
142
}
146

            
147
568
fn is_plain_text_failure(response: &Response) -> bool {
148
568
    response.status().as_u16() >= 400
149
215
        && response.extensions().get::<WebError>().is_none()
150
74
        && header_str(response.headers(), header::CONTENT_TYPE.as_str())
151
73
            .is_some_and(|content_type| content_type.starts_with("text/plain"))
152
568
}
153

            
154
10
async fn rejection_message(status: StatusCode, body: Body) -> String {
155
10
    let text = match to_bytes(body, REJECTION_BODY_LIMIT).await {
156
8
        Ok(bytes) => String::from_utf8_lossy(&bytes).trim().to_string(),
157
2
        Err(_) => String::new(),
158
    };
159
10
    match text.is_empty() {
160
2
        true => status.canonical_reason().unwrap_or("Error").to_string(),
161
8
        false => text.chars().take(REJECTION_MESSAGE_CHARS).collect(),
162
    }
163
10
}
164

            
165
/// Extractor rejections answer plain text; turned into a `WebError` they render like every other failure.
166
568
pub async fn adopt_rejection(response: Response) -> Response {
167
568
    if !is_plain_text_failure(&response) {
168
558
        return response;
169
10
    }
170
10
    let (parts, body) = response.into_parts();
171
10
    let message = rejection_message(parts.status, body).await;
172
10
    let mut adopted = WebError::new(parts.status, message).into_response();
173
10
    carry_headers(&parts.headers, &mut adopted);
174
10
    adopted
175
568
}
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.
179
542
pub async fn render_web_error(req: Request<Body>, next: Next) -> Response {
180
542
    let format = Format::of(req.headers());
181
542
    let page = Format::Page {
182
542
        back: back_link(req.headers()),
183
542
    };
184
542
    let response = next.run(req).await;
185
542
    let format = match (format, response.extensions().get::<FullPage>()) {
186
90
        (Format::Json, Some(_)) => page,
187
452
        (format, _) => format,
188
    };
189
542
    let response = adopt_rejection(response).await;
190
542
    let Some(error) = response.extensions().get::<WebError>().cloned() else {
191
400
        return response;
192
    };
193
142
    match render(&error, format) {
194
        Some(mut rendered) => {
195
86
            carry_headers(response.headers(), &mut rendered);
196
86
            rendered
197
        }
198
56
        None => response,
199
    }
200
542
}
201

            
202
#[cfg(test)]
203
#[path = "error_render_tests.rs"]
204
mod tests;