1use 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
29pub trait ErrorPages: Send + Sync + 'static {
36 fn render<'a>(
38 &'a self,
39 request: &'a ErrorContext,
40 error: &'a AppError,
41 ) -> BoxFuture<'a, Option<Response>>;
42}
43
44#[derive(Clone)]
46pub struct ErrorPagesHandle(pub(crate) Arc<dyn ErrorPages>);
47
48impl ErrorPagesHandle {
49 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#[derive(Clone, Debug)]
63pub struct ErrorContext {
64 pub method: Method,
66 pub uri: Uri,
68 pub headers: HeaderMap,
74 pub ctx: AppContext,
76 pub request_id: Option<RequestId>,
78 pub route: Option<Arc<RouteMeta>>,
83 pub user: Option<Uuid>,
86 pub api_prefix: Arc<str>,
88 pub(crate) matched: Option<Arc<OnceLock<Arc<RouteMeta>>>>,
90 pub(crate) finder: Option<RouteFinder>,
92}
93
94impl ErrorContext {
95 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 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 pub fn path(&self) -> &str {
125 self.uri.path()
126 }
127
128 pub fn is_api_path(&self) -> bool {
130 under(self.uri.path(), &self.api_prefix)
131 }
132
133 pub fn accepts(&self) -> Preference {
135 preference(&self.headers)
136 }
137}
138
139fn 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
150pub enum Preference {
151 Html,
153 Json,
155 Either,
157}
158
159const MOST_RANGES: usize = 32;
161
162pub 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 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#[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
250fn 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#[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 pub(crate) fn add(&mut self, method: Method, meta: &Arc<RouteMeta>) {
286 let meta = meta.clone();
287 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 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
338pub(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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
364#[non_exhaustive]
365pub enum RouteKind {
366 #[default]
368 Auto,
369 Page,
371 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 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 #[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}