Skip to main content

navree_http/
error_pages.rs

1//! [`ErrorPages`]: a module's way to answer an error with something other than
2//! the JSON error body, such as a page for a browser, and the request facts it
3//! decides with.
4//!
5//! The pipeline renders every error. When a module has contributed an
6//! [`ErrorPages`] ([`ModuleBuilderHttpExt::error_pages`](crate::ModuleBuilderHttpExt::error_pages)),
7//! it is asked first, with an [`ErrorContext`] describing the request; an answer
8//! of `None` leaves the JSON body as it is. A route that asked for JSON with
9//! [`RouteDef::json_only`](crate::RouteDef::json_only) is never asked.
10
11use std::sync::Arc;
12
13use http::header::{self, HeaderMap, HeaderName};
14use std::convert::Infallible;
15use std::sync::OnceLock;
16
17use http::{Method, Uri};
18use navree_contracts::RequestId;
19use navree_kernel::{AppContext, BoxFuture};
20use tower::ServiceExt;
21use tower::util::BoxCloneSyncService;
22use uuid::Uuid;
23
24use crate::body::Body;
25use crate::extract::Request;
26use crate::response::Response;
27use crate::{AppError, RouteMeta, routing};
28
29/// Answers errors in another form than JSON.
30///
31/// `render` returns the whole response for `error` (status and body), or `None`
32/// to keep the JSON body. It runs on the error path only, never for a response
33/// that succeeded. It must not panic and should not fail: when it cannot build
34/// its answer it returns `None`, and the client gets the JSON body.
35pub trait ErrorPages: Send + Sync + 'static {
36    /// The response for `error`, or `None` for the JSON body.
37    fn render<'a>(
38        &'a self,
39        request: &'a ErrorContext,
40        error: &'a AppError,
41    ) -> BoxFuture<'a, Option<Response>>;
42}
43
44/// An [`ErrorPages`] as a module contributes it.
45#[derive(Clone)]
46pub struct ErrorPagesHandle(pub(crate) Arc<dyn ErrorPages>);
47
48impl ErrorPagesHandle {
49    /// Wraps `pages`.
50    pub fn new(pages: impl ErrorPages) -> Self {
51        Self(Arc::new(pages))
52    }
53}
54
55impl std::fmt::Debug for ErrorPagesHandle {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.write_str("ErrorPagesHandle")
58    }
59}
60
61/// What the pipeline knows about the request that ended in an error.
62#[derive(Clone, Debug)]
63pub struct ErrorContext {
64    /// The request's method.
65    pub method: Method,
66    /// The request's URI, as it arrived.
67    pub uri: Uri,
68    /// The headers a page can depend on: `Accept`, `Accept-Language`, `Cookie`,
69    /// `Host`, `User-Agent` (a native client's web view is known by it), the
70    /// `Sec-Fetch-*` and `Sec-Purpose` headers, `X-Requested-With` and every
71    /// `X-Navree-*` header. Nothing else is kept: not
72    /// `Authorization`, not an API key, not the body.
73    pub headers: HeaderMap,
74    /// The app.
75    pub ctx: AppContext,
76    /// The request id, when the request had one.
77    pub request_id: Option<RequestId>,
78    /// The route the request belongs to: the one that handled it, or, for an error
79    /// raised before any route ran (a refused CSRF token, a limit, a 405), the route its
80    /// path and method name (for a 405, the route of the first method the path takes).
81    /// `None` when no route has that path.
82    pub route: Option<Arc<RouteMeta>>,
83    /// The signed-in user, when the request reached authentication and had one.
84    /// A panic or a timeout cannot say, and leaves it `None`.
85    pub user: Option<Uuid>,
86    /// `http.api_prefix`: paths under it belong to the JSON API.
87    pub api_prefix: Arc<str>,
88    /// The route the request reached, filled in as it reaches one.
89    pub(crate) matched: Option<Arc<OnceLock<Arc<RouteMeta>>>>,
90    /// Finds a request's route without running it.
91    pub(crate) finder: Option<RouteFinder>,
92}
93
94impl ErrorContext {
95    /// A context for `method` and `uri` in the app `ctx`, with no headers, no request id, no
96    /// route and no user, and `/api` as the API prefix. Set the public fields for what your
97    /// test or tool knows.
98    pub fn new(method: Method, uri: Uri, ctx: AppContext) -> Self {
99        Self {
100            method,
101            uri,
102            headers: HeaderMap::new(),
103            ctx,
104            request_id: None,
105            route: None,
106            user: None,
107            api_prefix: Arc::from("/api"),
108            matched: None,
109            finder: None,
110        }
111    }
112
113    /// The route this request belongs to, for an error. A route that ran has set it; for one
114    /// raised before any route ran, the router is asked which route the path names, without
115    /// running it. Only an error pays for this.
116    pub(crate) async fn resolve_route(&self) -> Option<Arc<RouteMeta>> {
117        if let Some(route) = self.matched.as_ref().and_then(|cell| cell.get()) {
118            return Some(route.clone());
119        }
120        self.finder.as_ref()?.find(&self.method, &self.uri).await
121    }
122
123    /// The path of the request.
124    pub fn path(&self) -> &str {
125        self.uri.path()
126    }
127
128    /// Whether the request path is under `http.api_prefix`.
129    pub fn is_api_path(&self) -> bool {
130        under(self.uri.path(), &self.api_prefix)
131    }
132
133    /// What the `Accept` header prefers.
134    pub fn accepts(&self) -> Preference {
135        preference(&self.headers)
136    }
137}
138
139/// Whether `path` is `prefix` or below it (`/api` holds `/api` and `/api/v1`, not `/apiary`).
140fn under(path: &str, prefix: &str) -> bool {
141    let prefix = prefix.trim_end_matches('/');
142    !prefix.is_empty()
143        && path
144            .strip_prefix(prefix)
145            .is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
146}
147
148/// What a client asked for in `Accept`.
149#[derive(Clone, Copy, Debug, PartialEq, Eq)]
150pub enum Preference {
151    /// A page: `text/html` or `application/xhtml+xml` is listed, and not behind JSON.
152    Html,
153    /// Data: JSON is listed, and not behind HTML.
154    Json,
155    /// No preference: no header, only wildcards, a tie, or neither type listed.
156    Either,
157}
158
159/// At most this many media ranges of one `Accept` header are read; the rest are ignored.
160const MOST_RANGES: usize = 32;
161
162/// What the `Accept` header of `headers` prefers.
163///
164/// The most specific range that matches a type sets its quality (RFC 9110
165/// section 12.5.1). An explicit range (`text/html`, `application/json`) beats
166/// a wildcard (`*/*`, `text/*`, `application/*`), so a browser's
167/// `text/html,...,*/*;q=0.8` is a page and a script's `application/json, */*`
168/// is data. When both are explicit the higher quality wins and a tie goes to the
169/// one listed first. A malformed range counts for nothing; an absurdly long
170/// header is read only as far as `MOST_RANGES` ranges.
171pub fn preference(headers: &HeaderMap) -> Preference {
172    let mut html = Rank::default();
173    let mut json = Rank::default();
174    let mut position = 0_usize;
175    for value in headers.get_all(header::ACCEPT) {
176        let Ok(text) = value.to_str() else { continue };
177        for range in text.split(',').take(MOST_RANGES) {
178            position += 1;
179            let mut parts = range.split(';');
180            let Some(media) = parts.next() else { continue };
181            let media = media.trim().to_ascii_lowercase();
182            let Some((kind, subtype)) = media.split_once('/') else {
183                continue;
184            };
185            let quality = quality_of(parts);
186            // Which of the two this range speaks for, and how exactly.
187            let (for_html, for_json, exact) = match (kind, subtype) {
188                ("text", "html") | ("application", "xhtml+xml") => (true, false, true),
189                ("application", "json") => (false, true, true),
190                ("application", s) if s.ends_with("+json") => (false, true, true),
191                ("*", "*") => (true, true, false),
192                ("text", "*") => (true, false, false),
193                ("application", "*") => (false, true, false),
194                _ => continue,
195            };
196            if for_html {
197                html.add(quality, exact, position);
198            }
199            if for_json {
200                json.add(quality, exact, position);
201            }
202        }
203    }
204    match (html.exact, json.exact) {
205        (Some(h), Some(j)) => {
206            if h.quality > j.quality || (h.quality == j.quality && h.position < j.position) {
207                if h.quality > 0.0 {
208                    Preference::Html
209                } else {
210                    Preference::Either
211                }
212            } else if j.quality > 0.0 {
213                Preference::Json
214            } else {
215                Preference::Either
216            }
217        }
218        (Some(h), None) if h.quality > 0.0 => Preference::Html,
219        (None, Some(j)) if j.quality > 0.0 => Preference::Json,
220        _ => Preference::Either,
221    }
222}
223
224/// The quality and place of the best exact range for one type.
225#[derive(Default)]
226struct Rank {
227    exact: Option<Found>,
228}
229
230#[derive(Clone, Copy)]
231struct Found {
232    quality: f32,
233    position: usize,
234}
235
236impl Rank {
237    fn add(&mut self, quality: f32, exact: bool, position: usize) {
238        if !exact {
239            return;
240        }
241        let better = self.exact.is_none_or(|have| {
242            quality > have.quality || (quality == have.quality && position < have.position)
243        });
244        if better {
245            self.exact = Some(Found { quality, position });
246        }
247    }
248}
249
250/// The `q` parameter of a media range, from 0 to 1; 1 when it has none or can't be read.
251fn quality_of<'a>(parameters: impl Iterator<Item = &'a str>) -> f32 {
252    for parameter in parameters {
253        let Some((name, value)) = parameter.split_once('=') else {
254            continue;
255        };
256        if name.trim().eq_ignore_ascii_case("q") {
257            return value
258                .trim()
259                .parse::<f32>()
260                .ok()
261                .filter(|q| q.is_finite())
262                .map_or(1.0, |q| q.clamp(0.0, 1.0));
263        }
264    }
265    1.0
266}
267
268/// Finds the route a request names with the router's own matching, without running the route.
269///
270/// It is a second [`routing::Router`] with the same paths, whose services answer with the route's
271/// metadata in place of its handler, so what matches here is exactly what matches there.
272#[derive(Clone)]
273pub(crate) struct RouteFinder {
274    router: routing::Router,
275}
276
277impl RouteFinder {
278    pub(crate) fn new() -> Self {
279        Self {
280            router: routing::Router::new(),
281        }
282    }
283
284    /// Adds `meta`'s route.
285    pub(crate) fn add(&mut self, method: Method, meta: &Arc<RouteMeta>) {
286        let meta = meta.clone();
287        // A mistake here would be the same mistake the real router already refused.
288        let _ = self
289            .router
290            .try_route_service(method, &meta.full_path.clone(), move || {
291                BoxCloneSyncService::new(tower::service_fn(move |_request: Request| {
292                    let meta = meta.clone();
293                    async move {
294                        let mut response = Response::new(Body::empty());
295                        response.extensions_mut().insert(meta);
296                        Ok::<_, Infallible>(response)
297                    }
298                }))
299            });
300    }
301
302    async fn find(&self, method: &Method, uri: &Uri) -> Option<Arc<RouteMeta>> {
303        let ask = |method: &Method| {
304            let mut request = Request::new(Body::empty());
305            *request.method_mut() = method.clone();
306            *request.uri_mut() = uri.clone();
307            self.router.clone().oneshot(request)
308        };
309        let response = ask(method).await.ok()?;
310        if let Some(meta) = response.extensions().get::<Arc<RouteMeta>>() {
311            return Some(meta.clone());
312        }
313        // A 405 names the methods the path takes: the route of the first of them is the path's.
314        let allow = response.headers().get(header::ALLOW)?.to_str().ok()?;
315        for name in allow.split(',').map(str::trim) {
316            if name.eq_ignore_ascii_case("OPTIONS") || name.eq_ignore_ascii_case("HEAD") {
317                continue;
318            }
319            let Ok(other) = Method::from_bytes(name.as_bytes()) else {
320                continue;
321            };
322            if let Ok(response) = ask(&other).await
323                && let Some(meta) = response.extensions().get::<Arc<RouteMeta>>()
324            {
325                return Some(meta.clone());
326            }
327        }
328        None
329    }
330}
331
332impl std::fmt::Debug for RouteFinder {
333    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
334        f.write_str("RouteFinder")
335    }
336}
337
338/// The request headers an [`ErrorContext`] keeps: what decides a page and
339/// nothing a handler or a secret could hide in.
340pub(crate) fn capture(headers: &HeaderMap) -> HeaderMap {
341    let mut kept = HeaderMap::with_capacity(4);
342    for (name, value) in headers {
343        if kept_header(name) {
344            kept.append(name.clone(), value.clone());
345        }
346    }
347    kept
348}
349
350fn kept_header(name: &HeaderName) -> bool {
351    *name == header::ACCEPT
352        || *name == header::ACCEPT_LANGUAGE
353        || *name == header::COOKIE
354        || *name == header::HOST
355        || *name == header::USER_AGENT
356        || name.as_str().starts_with("sec-fetch-")
357        || name.as_str() == "sec-purpose"
358        || name.as_str() == "x-requested-with"
359        || name.as_str().starts_with("x-navree-")
360}
361
362/// How a route's errors are shown (see [`RouteDef::page`](crate::RouteDef::page)).
363#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
364#[non_exhaustive]
365pub enum RouteKind {
366    /// Not said: the `Accept` header and the request's path decide.
367    #[default]
368    Auto,
369    /// A page: its errors are pages for any client that doesn't ask for JSON alone.
370    Page,
371    /// Data: its errors are always JSON.
372    Json,
373}
374
375#[cfg(test)]
376mod tests {
377    use http::header::HeaderValue;
378
379    use super::*;
380
381    fn accept(value: &str) -> Preference {
382        let mut headers = HeaderMap::new();
383        headers.insert(
384            header::ACCEPT,
385            HeaderValue::from_str(value).expect("a header"),
386        );
387        preference(&headers)
388    }
389
390    #[test]
391    fn a_browser_navigation_is_a_page() {
392        assert_eq!(
393            accept("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,*/*;q=0.8"),
394            Preference::Html
395        );
396        assert_eq!(accept("application/xhtml+xml"), Preference::Html);
397        assert_eq!(accept("TEXT/HTML"), Preference::Html);
398    }
399
400    #[test]
401    fn a_script_asking_for_json_gets_json() {
402        assert_eq!(accept("application/json"), Preference::Json);
403        assert_eq!(
404            accept("application/json, text/plain, */*"),
405            Preference::Json
406        );
407        assert_eq!(accept("application/problem+json"), Preference::Json);
408        assert_eq!(
409            accept("application/vnd.api+json;q=0.9, */*"),
410            Preference::Json
411        );
412    }
413
414    #[test]
415    fn json_listed_alone_never_gets_a_page() {
416        assert_eq!(accept("application/json;q=0.1"), Preference::Json);
417        assert_eq!(accept("text/html;q=0, application/json"), Preference::Json);
418    }
419
420    #[test]
421    fn wildcards_and_nothing_say_nothing() {
422        assert_eq!(preference(&HeaderMap::new()), Preference::Either);
423        assert_eq!(accept("*/*"), Preference::Either);
424        assert_eq!(accept("text/*"), Preference::Either);
425        assert_eq!(accept("application/*, */*;q=0.1"), Preference::Either);
426        assert_eq!(accept("image/png"), Preference::Either);
427        assert_eq!(accept("text/plain"), Preference::Either);
428    }
429
430    #[test]
431    fn the_higher_quality_wins_and_a_tie_goes_to_the_first() {
432        assert_eq!(
433            accept("text/html;q=0.1, application/json"),
434            Preference::Json
435        );
436        assert_eq!(
437            accept("text/html, application/json;q=0.5"),
438            Preference::Html
439        );
440        assert_eq!(accept("application/json, text/html"), Preference::Json);
441        assert_eq!(accept("text/html, application/json"), Preference::Html);
442    }
443
444    #[test]
445    fn a_page_refused_outright_is_not_a_page() {
446        assert_eq!(accept("text/html;q=0"), Preference::Either);
447        assert_eq!(accept("text/html;q=0, */*"), Preference::Either);
448    }
449
450    #[test]
451    fn malformed_values_are_read_as_far_as_they_make_sense() {
452        for value in [
453            "",
454            ",,,",
455            ";;;",
456            "text/html;q=",
457            "text/html;q=abc",
458            "text/html;q=NaN",
459            "text/html;q=1e999",
460            "text/html;q=-1",
461            "text",
462            "/",
463            "a/b/c",
464            "text/html;;;;q=0.5",
465            "\u{e9}/\u{e9}",
466        ] {
467            // None of these panics; what each means is covered above.
468            let _ = accept(value);
469        }
470        assert_eq!(accept("text/html;q=abc"), Preference::Html);
471        assert_eq!(accept("text/html;q=1e999"), Preference::Html);
472        assert_eq!(accept("text/html;q=-1"), Preference::Either);
473    }
474
475    #[test]
476    fn a_header_that_is_not_text_is_ignored() {
477        let mut headers = HeaderMap::new();
478        headers.insert(
479            header::ACCEPT,
480            HeaderValue::from_bytes(b"text/html\xff").unwrap(),
481        );
482        assert_eq!(preference(&headers), Preference::Either);
483    }
484
485    #[test]
486    fn a_very_long_header_is_read_only_so_far() {
487        let long = format!("{}text/html", "image/png,".repeat(5000));
488        assert_eq!(accept(&long), Preference::Either);
489        let early = format!("text/html,{}", "image/png,".repeat(5000));
490        assert_eq!(accept(&early), Preference::Html);
491    }
492
493    #[test]
494    fn two_headers_are_read_as_one_list() {
495        let mut headers = HeaderMap::new();
496        headers.append(header::ACCEPT, HeaderValue::from_static("application/json"));
497        headers.append(header::ACCEPT, HeaderValue::from_static("text/html;q=0.5"));
498        assert_eq!(preference(&headers), Preference::Json);
499    }
500
501    #[test]
502    fn api_paths_are_the_prefix_and_below() {
503        assert!(under("/api", "/api"));
504        assert!(under("/api/v1/deals", "/api"));
505        assert!(under("/api/v1", "/api/"));
506        assert!(!under("/apiary", "/api"));
507        assert!(!under("/", "/api"));
508        assert!(!under("/api", ""));
509    }
510
511    /// Every request pays this when a module renders error pages: it must stay a rounding error.
512    #[cfg(not(debug_assertions))]
513    #[test]
514    fn keeping_what_a_page_needs_costs_under_2_us() {
515        use std::hint::black_box;
516        use std::time::{Duration, Instant};
517        let mut headers = HeaderMap::new();
518        for (name, value) in [
519            ("host", "app.example"),
520            (
521                "user-agent",
522                "Mozilla/5.0 (X11; Linux x86_64) Firefox/144.0",
523            ),
524            ("accept", "text/html,application/xhtml+xml,*/*;q=0.8"),
525            ("accept-language", "en-US,en;q=0.5"),
526            ("accept-encoding", "gzip, deflate, br"),
527            ("referer", "https://app.example/deals"),
528            ("cookie", "navree_session=abcdef; XSRF-TOKEN=abcdef"),
529            ("sec-fetch-dest", "document"),
530            ("sec-fetch-mode", "navigate"),
531            ("sec-fetch-site", "same-origin"),
532            ("upgrade-insecure-requests", "1"),
533            ("x-request-id", "01a1a48c27697468b09935ddd4286017"),
534        ] {
535            headers.append(
536                HeaderName::from_bytes(name.as_bytes()).unwrap(),
537                HeaderValue::from_static(value),
538            );
539        }
540        black_box(capture(&headers));
541        let best = (0..2000)
542            .map(|_| {
543                let start = Instant::now();
544                black_box(capture(black_box(&headers)));
545                start.elapsed()
546            })
547            .min()
548            .unwrap();
549        println!("keeping the headers a page needs takes {best:?}");
550        assert!(best < Duration::from_micros(2), "{best:?}");
551    }
552
553    #[test]
554    fn only_what_decides_a_page_is_kept() {
555        let mut headers = HeaderMap::new();
556        for (name, value) in [
557            ("accept", "text/html"),
558            ("cookie", "a=b"),
559            ("authorization", "Bearer secret"),
560            ("x-api-key", "secret"),
561            ("x-navree-ui", "1"),
562            ("sec-fetch-dest", "document"),
563            ("user-agent", "x"),
564        ] {
565            headers.append(
566                HeaderName::from_bytes(name.as_bytes()).unwrap(),
567                HeaderValue::from_static(value),
568            );
569        }
570        let kept = capture(&headers);
571        let mut names: Vec<&str> = kept.keys().map(HeaderName::as_str).collect();
572        names.sort_unstable();
573        assert_eq!(
574            names,
575            [
576                "accept",
577                "cookie",
578                "sec-fetch-dest",
579                "user-agent",
580                "x-navree-ui"
581            ]
582        );
583    }
584}