Skip to main content

rws_http/error/
page.rs

1//! The HTML page rws shows a browser for its own errors (18.37.0): 404,
2//! 502, 503, maintenance and the rest. One self-contained template (inline
3//! CSS, light and dark, a title, the status, one sentence, a link home) in
4//! the look of the directory listing.
5//!
6//! API clients are unchanged: [`negotiated`] turns an
7//! `application/problem+json` response into this page only when the
8//! request's `Accept` prefers `text/html` (a browser navigation). Under a
9//! `Content-Security-Policy` that forbids inline styles the page still
10//! reads, unstyled.
11
12use crate::request::Request;
13use crate::response::Response;
14
15/// Whether the request prefers HTML: `Accept` lists `text/html` (not with
16/// `q=0`) ahead of any JSON type. `*/*` alone (fetch, curl) is not HTML.
17pub fn wants_html(request: &Request) -> bool {
18    let Some(accept) = request.header("Accept") else { return false };
19    for part in accept.value.split(',') {
20        let mut fields = part.split(';');
21        let kind = fields.next().unwrap_or("").trim().to_ascii_lowercase();
22        let refused = fields.any(|f| {
23            let f = f.trim();
24            f.strip_prefix("q=").is_some_and(|q| q.trim().parse::<f32>().is_ok_and(|q| q == 0.0))
25        });
26        if kind.contains("json") {
27            return false;
28        }
29        if kind == "text/html" || kind == "application/xhtml+xml" {
30            return !refused;
31        }
32    }
33    false
34}
35
36/// The sentence under the status for a code.
37fn sentence(status: i16, detail: &str) -> String {
38    match status {
39        404 => "There is nothing at this address. Check the link for typos, or start from the home page.".to_string(),
40        403 => "You don't have access to this page.".to_string(),
41        401 => "This page needs you to sign in.".to_string(),
42        429 => "Too many requests from your address. Wait a moment, then try again.".to_string(),
43        502 => "The server behind this site didn't answer properly. Try again in a moment.".to_string(),
44        504 => "The server behind this site took too long to answer. Try again in a moment.".to_string(),
45        503 if detail == "maintenance" => maintenance_message(),
46        503 => "This site can't answer right now. Try again in a moment.".to_string(),
47        s if s >= 500 => "Something went wrong on the server. Try again in a moment.".to_string(),
48        _ => "The request couldn't be completed.".to_string(),
49    }
50}
51
52/// `[maintenance] message` (`RWS_CONFIG_MAINTENANCE_MESSAGE`), or the default.
53pub fn maintenance_message() -> String {
54    std::env::var("RWS_CONFIG_MAINTENANCE_MESSAGE")
55        .ok()
56        .map(|m| m.trim().to_string())
57        .filter(|m| !m.is_empty())
58        .unwrap_or_else(|| "This site is down for maintenance. It will be back shortly.".to_string())
59}
60
61/// `Retry-After` seconds sent with maintenance responses
62/// (`RWS_CONFIG_MAINTENANCE_RETRY_AFTER_SECS`, default 120; 0 sends none).
63pub fn maintenance_retry_after() -> u64 {
64    std::env::var("RWS_CONFIG_MAINTENANCE_RETRY_AFTER_SECS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(120)
65}
66
67fn escape(s: &str) -> String {
68    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
69}
70
71/// The page for `status`/`reason`; `detail` picks the sentence
72/// (`"maintenance"`) and is otherwise not shown (it may be technical).
73pub fn html(status: i16, reason: &str, detail: &str) -> String {
74    let title = if status == 503 && detail == "maintenance" { "Down for maintenance".to_string() } else { reason.to_string() };
75    format!(
76        concat!(
77            "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n",
78            "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n",
79            "<meta name=\"robots\" content=\"noindex\">\n",
80            "<title>{status} {title}</title>\n<style>\n{css}</style>\n</head>\n<body>\n",
81            "<main>\n<p class=\"code\">{status}</p>\n<h1>{title}</h1>\n<p>{sentence}</p>\n",
82            "<p><a href=\"/\">Go to the home page</a></p>\n</main>\n",
83            "<footer>served by rws</footer>\n</body>\n</html>\n",
84        ),
85        status = status,
86        title = escape(&title),
87        sentence = escape(&sentence(status, detail)),
88        css = CSS,
89    )
90}
91
92const CSS: &str = ":root{color-scheme:light dark;--bg:#f7f7f9;--text:#1b1f27;--muted:#4b5563;--accent:#c2410c}
93@media (prefers-color-scheme:dark){:root{--bg:#0b0d12;--text:#e7e9ee;--muted:#a3acb9;--accent:#fb923c}}
94*{box-sizing:border-box}
95body{margin:0;min-height:100vh;display:flex;flex-direction:column;justify-content:center;background:var(--bg);color:var(--text);font:16px/1.55 -apple-system,BlinkMacSystemFont,\"Segoe UI\",Inter,Roboto,sans-serif;padding:2rem 1rem}
96main{max-width:34rem;margin:0 auto;width:100%}
97.code{margin:0;font:600 .85rem/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.08em;color:var(--muted)}
98h1{margin:.4rem 0 .75rem;font-size:1.75rem;line-height:1.2;letter-spacing:-.02em}
99p{margin:0 0 1rem;color:var(--muted)}
100a{color:var(--accent);font-weight:600;text-underline-offset:3px;display:inline-block;padding:.5rem 0}
101a:focus-visible{outline:2px solid var(--accent);outline-offset:3px;border-radius:4px}
102footer{margin-top:3rem;text-align:center;color:var(--muted);font-size:.8rem}
103";
104
105/// `response` as the HTML page when it is an rws-made problem details
106/// response (`application/problem+json`) and `request` prefers HTML;
107/// otherwise unchanged.
108pub fn negotiated(mut response: Response, request: &Request) -> Response {
109    if !wants_html(request) {
110        return response;
111    }
112    let Some(part) = response.content_range_list.first() else { return response };
113    if part.content_type != super::problem::PROBLEM_JSON || response.content_range_list.len() != 1 {
114        return response;
115    }
116    let body = String::from_utf8_lossy(&part.body);
117    let detail = body
118        .split_once("\"detail\":\"")
119        .and_then(|(_, rest)| rest.split_once('"'))
120        .map(|(d, _)| d.to_string())
121        .unwrap_or_default();
122    let page = html(response.status_code, &response.reason_phrase, &detail);
123    response.content_range_list = vec![crate::range::Range::get_content_range(page.into_bytes(), crate::mime_type::MimeType::TEXT_HTML.to_string())];
124    if !response.headers.iter().any(|h| h.name.eq_ignore_ascii_case("Vary") && h.value.to_ascii_lowercase().contains("accept")) {
125        response.headers.push(crate::header::Header { name: "Vary".into(), value: "Accept".into() });
126    }
127    response
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    fn request(accept: Option<&str>) -> Request {
135        let head = match accept {
136            Some(a) => format!("GET / HTTP/1.1\r\nHost: x\r\nAccept: {a}\r\n\r\n"),
137            None => "GET / HTTP/1.1\r\nHost: x\r\n\r\n".to_string(),
138        };
139        Request::parse(head.as_bytes()).unwrap()
140    }
141
142    #[test]
143    fn browsers_get_html_api_clients_json() {
144        assert!(wants_html(&request(Some("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"))));
145        assert!(!wants_html(&request(Some("*/*"))));
146        assert!(!wants_html(&request(Some("application/json, text/html"))));
147        assert!(!wants_html(&request(Some("text/html;q=0"))));
148        assert!(!wants_html(&request(None)));
149    }
150
151    #[test]
152    fn problem_json_becomes_a_page_for_browsers_only() {
153        let browser = request(Some("text/html"));
154        let r = negotiated(crate::error::problem(crate::response::STATUS_CODE_REASON_PHRASE.n502_bad_gateway, ""), &browser);
155        let body = String::from_utf8_lossy(&r.content_range_list[0].body).to_string();
156        assert_eq!(r.content_range_list[0].content_type, "text/html");
157        assert!(body.contains("<title>502 Bad Gateway</title>") && body.contains("href=\"/\""));
158        let api = negotiated(crate::error::problem(crate::response::STATUS_CODE_REASON_PHRASE.n502_bad_gateway, ""), &request(Some("application/json")));
159        assert_eq!(api.content_range_list[0].body, br#"{"type":"about:blank","title":"Bad Gateway","status":502}"#.to_vec());
160    }
161
162    #[test]
163    fn maintenance_has_its_own_title() {
164        let page = html(503, "Service Unavailable", "maintenance");
165        assert!(page.contains("Down for maintenance"));
166    }
167}