Lines
100 %
Functions
69.05 %
Branches
use askama::Template;
use axum::{
body::{Body, to_bytes},
http::{HeaderMap, HeaderName, HeaderValue, Request, StatusCode, header},
middleware::Next,
response::{Html, IntoResponse, Redirect, Response},
};
use crate::response::WebError;
#[derive(Template)]
#[template(
source = r#"<div class="error-alert">{{ message }}</div>"#,
ext = "html"
)]
struct ErrorFragment<'a> {
message: &'a str,
}
#[template(path = "pages/error.html")]
struct ErrorPage<'a> {
status: u16,
back: &'a str,
enum Format {
Fragment,
Page { back: String },
Json,
impl Format {
fn of(headers: &HeaderMap) -> Self {
if header_str(headers, "hx-request") == Some("true") {
return Self::Fragment;
match header_str(headers, header::ACCEPT.as_str()) {
Some(accept) if accept.contains("text/html") => Self::Page {
back: back_link(headers),
},
_ => Self::Json,
fn header_str<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
headers.get(name).and_then(|v| v.to_str().ok())
/// The Referer's path when it points at this host, else the root.
fn back_link(headers: &HeaderMap) -> String {
let same_origin = header_str(headers, header::REFERER.as_str())
.and_then(|referer| referer.split_once("://"))
.and_then(|(_, rest)| rest.split_once('/').or(Some((rest, ""))))
.filter(|(host, _)| header_str(headers, header::HOST.as_str()) == Some(host));
match same_origin {
Some((_, path)) => format!("/{}", path.trim_start_matches(['/', '\\'])),
None => "/".to_string(),
/// Marks the response of a page route: its failure renders as a page
/// whatever the request accepts.
#[derive(Clone, Copy)]
struct FullPage;
/// Route layer of the page routers: a browser navigation never shows a
/// failure as raw JSON.
pub async fn full_page(req: Request<Body>, next: Next) -> Response {
let mut response = next.run(req).await;
response.extensions_mut().insert(FullPage);
response
const LOGIN: &str = "/login";
const REJECTION_BODY_LIMIT: usize = 1024;
const REJECTION_MESSAGE_CHARS: usize = 200;
const REPRESENTATION_HEADERS: [HeaderName; 5] = [
header::CONTENT_TYPE,
header::CONTENT_LENGTH,
header::CONTENT_ENCODING,
header::ETAG,
header::LAST_MODIFIED,
];
/// Keeps the headers of the replaced response (rotated session cookies above all);
/// only those describing the old body and ones the replacement already set are dropped.
fn carry_headers(from: &HeaderMap, to: &mut Response) {
for name in from.keys() {
if REPRESENTATION_HEADERS.contains(name) || to.headers().contains_key(name) {
continue;
for value in from.get_all(name) {
to.headers_mut().append(name.clone(), value.clone());
fn html_response(error: &WebError, rendered: askama::Result<String>) -> Option<Response> {
let html = rendered.ok()?;
let mut response = (error.status, Html(html)).into_response();
response.headers_mut().insert(
HeaderValue::from_static("text/html; charset=utf-8"),
);
Some(response)
/// Not logged in is not an error to display: the client is sent to log in.
/// htmx performs `HX-Redirect` whatever the status, so the 401 is kept.
fn login_redirect(format: Format) -> Option<Response> {
match format {
Format::Page { .. } => Some(Redirect::to(LOGIN).into_response()),
Format::Fragment => Some(
(
StatusCode::UNAUTHORIZED,
[("HX-Redirect", HeaderValue::from_static(LOGIN))],
)
.into_response(),
),
Format::Json => None,
fn render(error: &WebError, format: Format) -> Option<Response> {
if error.status == StatusCode::UNAUTHORIZED {
return login_redirect(format);
let rendered = match format {
Format::Fragment => ErrorFragment {
message: &error.message,
.render(),
Format::Page { back } => ErrorPage {
status: error.status.as_u16(),
back: &back,
Format::Json => return None,
html_response(error, rendered)
fn is_plain_text_failure(response: &Response) -> bool {
response.status().as_u16() >= 400
&& response.extensions().get::<WebError>().is_none()
&& header_str(response.headers(), header::CONTENT_TYPE.as_str())
.is_some_and(|content_type| content_type.starts_with("text/plain"))
async fn rejection_message(status: StatusCode, body: Body) -> String {
let text = match to_bytes(body, REJECTION_BODY_LIMIT).await {
Ok(bytes) => String::from_utf8_lossy(&bytes).trim().to_string(),
Err(_) => String::new(),
match text.is_empty() {
true => status.canonical_reason().unwrap_or("Error").to_string(),
false => text.chars().take(REJECTION_MESSAGE_CHARS).collect(),
/// Extractor rejections answer plain text; turned into a `WebError` they render like every other failure.
pub async fn adopt_rejection(response: Response) -> Response {
if !is_plain_text_failure(&response) {
return response;
let (parts, body) = response.into_parts();
let message = rejection_message(parts.status, body).await;
let mut adopted = WebError::new(parts.status, message).into_response();
carry_headers(&parts.headers, &mut adopted);
adopted
/// Re-renders a `WebError` response as an htmx fragment, an error page or JSON, by request;
/// a page route's failure is never JSON, and a 401 becomes a redirect to the login page.
pub async fn render_web_error(req: Request<Body>, next: Next) -> Response {
let format = Format::of(req.headers());
let page = Format::Page {
back: back_link(req.headers()),
let response = next.run(req).await;
let format = match (format, response.extensions().get::<FullPage>()) {
(Format::Json, Some(_)) => page,
(format, _) => format,
let response = adopt_rejection(response).await;
let Some(error) = response.extensions().get::<WebError>().cloned() else {
match render(&error, format) {
Some(mut rendered) => {
carry_headers(response.headers(), &mut rendered);
rendered
None => response,
#[cfg(test)]
#[path = "error_render_tests.rs"]
mod tests;