1use std::collections::HashMap;
2use std::fmt::{Display, Write};
3
4use std::convert::Infallible;
5
6use anyhow::{anyhow, bail};
7use axum::Router;
8use axum::extract::Request;
9use axum::handler::Handler;
10use axum::middleware::from_fn;
11use axum::response::IntoResponse;
12use axum::routing::{self, MethodRouter, Route};
13use tower::{Layer, Service};
14
15use crate::AppState;
16
17#[derive(Default)]
32pub struct Routes {
33 router: Router<AppState>,
34 names: Vec<(String, String)>,
35 last_path: Option<String>,
36 listing: Vec<RouteInfo>,
37 fallback: Option<MethodRouter<AppState>>,
38 domains: Vec<(String, Routes)>,
39}
40
41pub(crate) struct RouteParts {
43 pub router: Router<AppState>,
44 pub names: Vec<(String, String)>,
45 pub listing: Vec<RouteInfo>,
46 pub fallback: Option<MethodRouter<AppState>>,
47 pub domains: Vec<(String, Routes)>,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52#[non_exhaustive]
53pub struct RouteInfo {
54 pub method: String,
56 pub path: String,
58 pub name: Option<String>,
60 pub module: String,
62 pub middleware: Vec<String>,
64 pub domain: Option<String>,
66}
67
68macro_rules! method {
69 ($($method:ident),*) => {$(
70 pub fn $method<H, T>(self, path: &str, handler: H) -> Self
72 where
73 H: Handler<T, AppState>,
74 T: 'static,
75 {
76 self.add(path, routing::$method(handler), &stringify!($method).to_uppercase())
77 }
78 )*};
79}
80
81impl Routes {
82 pub fn new() -> Self {
84 Self::default()
85 }
86
87 method!(get, post, put, patch, delete);
88
89 pub fn resource(mut self, path: &str, name: &str, resource: Resource) -> Self {
115 assert!(
116 path.starts_with('/') && !path.ends_with('/'),
117 "Routes::resource(\"{path}\", …): the path must start with `/` and not end with one"
118 );
119 let member = format!("{path}/{{id}}");
120 let actions = [
121 ("index", "GET", path.to_owned(), resource.index),
122 ("create", "GET", format!("{path}/new"), resource.create),
123 ("store", "POST", path.to_owned(), resource.store),
124 ("show", "GET", member.clone(), resource.show),
125 ("edit", "GET", format!("{member}/edit"), resource.edit),
126 ("update", "PUT", member.clone(), resource.update),
127 ("destroy", "DELETE", member, resource.destroy),
128 ];
129 for (action, method, at, router) in actions {
130 if let Some(router) = router {
131 let method = if action == "update" {
132 "PUT|PATCH"
133 } else {
134 method
135 };
136 self = self
137 .add(&at, router, method)
138 .name(&format!("{name}.{action}"));
139 }
140 }
141 self
142 }
143
144 pub fn route(self, path: &str, method_router: MethodRouter<AppState>) -> Self {
146 self.add(path, method_router, "*")
147 }
148
149 pub fn view(self, path: &str, template: &str) -> Self {
159 let template = template.to_owned();
160 self.add(
161 path,
162 axum::routing::get(move || {
163 let template = template.clone();
164 async move { crate::view(&template, minijinja::context! {}) }
165 }),
166 "GET",
167 )
168 }
169
170 pub fn redirect(self, path: &str, to: &str) -> Self {
173 let to = to.to_owned();
174 self.add(
175 path,
176 axum::routing::any(move || {
177 let to = to.clone();
178 async move { redirect_with(axum::http::StatusCode::FOUND, &to) }
179 }),
180 "*",
181 )
182 }
183
184 pub fn permanent_redirect(self, path: &str, to: &str) -> Self {
186 let to = to.to_owned();
187 self.add(
188 path,
189 axum::routing::any(move || {
190 let to = to.clone();
191 async move { redirect_with(axum::http::StatusCode::MOVED_PERMANENTLY, &to) }
192 }),
193 "*",
194 )
195 }
196
197 fn add(mut self, path: &str, method_router: MethodRouter<AppState>, method: &str) -> Self {
198 self.router = self.router.route(path, method_router);
199 self.last_path = Some(path.to_owned());
200 self.listing.push(RouteInfo {
201 method: method.to_owned(),
202 path: path.to_owned(),
203 name: None,
204 module: String::new(),
205 middleware: Vec::new(),
206 domain: None,
207 });
208 self
209 }
210
211 fn mark(mut self, middleware: &str) -> Self {
213 for route in &mut self.listing {
214 route.middleware.push(middleware.to_owned());
215 }
216 self
217 }
218
219 pub fn name(mut self, name: &str) -> Self {
225 let path = self
226 .last_path
227 .clone()
228 .expect("Routes::name() must follow a route");
229 self.names.push((name.to_owned(), path));
230 let path = self.last_path.clone();
234 for route in self.listing.iter_mut().rev() {
235 if Some(&route.path) != path.as_ref() {
236 break;
237 }
238 if route.name.is_none() {
239 route.name = Some(name.to_owned());
240 }
241 }
242 self
243 }
244
245 pub fn require_auth(self) -> Self {
248 self.route_layer(from_fn(crate::auth::require_auth))
249 .mark("auth")
250 }
251
252 pub fn require_verified(self) -> Self {
255 self.route_layer(from_fn(crate::auth::require_verified))
256 .mark("verified")
257 }
258
259 pub fn require_gate(self, name: &str) -> Self {
263 self.requirement(
264 crate::auth::Requirement::Gate(name.to_owned()),
265 "gate",
266 name,
267 )
268 }
269
270 pub fn require_role(self, role: &str) -> Self {
273 self.requirement(
274 crate::auth::Requirement::Role(role.to_owned()),
275 "role",
276 role,
277 )
278 }
279
280 pub fn require_permission(self, permission: &str) -> Self {
283 self.requirement(
284 crate::auth::Requirement::Permission(permission.to_owned()),
285 "permission",
286 permission,
287 )
288 }
289
290 pub fn require_ability(self, ability: &str) -> Self {
293 self.requirement(
294 crate::auth::Requirement::Ability(ability.to_owned()),
295 "ability",
296 ability,
297 )
298 }
299
300 pub fn require_device(self) -> Self {
304 self.device_guard(None, "device")
305 }
306
307 pub fn require_device_ability(self, ability: &str) -> Self {
310 self.device_guard(Some(ability), &format!("device:{ability}"))
311 }
312
313 fn device_guard(self, ability: Option<&str>, mark: &str) -> Self {
314 let ability = ability.map(|a| std::sync::Arc::new(a.to_owned()));
315 self.route_layer(from_fn(
316 move |req: Request, next: axum::middleware::Next| {
317 crate::auth::device_guard(ability.clone(), req, next)
318 },
319 ))
320 .mark(mark)
321 }
322
323 fn requirement(self, requirement: crate::auth::Requirement, kind: &str, name: &str) -> Self {
324 let requirement = std::sync::Arc::new(requirement);
325 self.route_layer(from_fn(
326 move |req: Request, next: axum::middleware::Next| {
327 crate::auth::require(requirement.clone(), req, next)
328 },
329 ))
330 .mark(&format!("{kind}:{name}"))
331 }
332
333 pub fn require_password_confirmed(self) -> Self {
337 self.route_layer(from_fn(crate::auth::require_password_confirmed))
338 .route_layer(from_fn(crate::auth::require_auth))
339 .mark("password.confirm")
340 }
341
342 pub fn guest_only(self) -> Self {
345 self.route_layer(from_fn(crate::auth::guest_only))
346 .mark("guest")
347 }
348
349 pub fn throttle(self, max: u32, per: std::time::Duration) -> Self {
352 let covered: Vec<String> = self
353 .listing
354 .iter()
355 .map(|route| format!("{} {}", route.method, route.path))
356 .collect();
357 let id =
358 crate::webhook::sha256_hex(format!("{}|{max}|{}", covered.join(","), per.as_secs()));
359 let limiter = std::sync::Arc::new(crate::rate_limit::Limiter::new(
360 id[..16].to_owned(),
361 max,
362 per,
363 ));
364 self.route_layer(from_fn(
365 move |req: Request, next: axum::middleware::Next| {
366 let limiter = limiter.clone();
367 async move { crate::rate_limit::check(&limiter, req, next).await }
368 },
369 ))
370 .mark(&format!("throttle:{max}/{}s", per.as_secs()))
371 }
372
373 pub fn throttle_by(self, name: &str) -> Self {
376 let owned = name.to_owned();
377 self.route_layer(from_fn(
378 move |req: Request, next: axum::middleware::Next| {
379 let name = owned.clone();
380 async move { crate::rate_limit::check_named(&name, req, next).await }
381 },
382 ))
383 .mark(&format!("throttle:{name}"))
384 }
385
386 pub fn webhook<W: crate::webhook::Webhook>(self, path: &str) -> Self {
391 let mut routes = self
392 .post(path, crate::webhook::receive::<W>)
393 .name(&format!("webhooks.{}", W::PROVIDER));
394 if let Some(route) = routes.listing.last_mut() {
395 route.middleware.push("no-csrf".into());
396 route.middleware.push(format!("webhook:{}", W::PROVIDER));
397 }
398 routes
399 }
400
401 pub fn etag(self) -> Self {
408 self.route_layer(from_fn(
409 |req: Request, next: axum::middleware::Next| async move {
410 let mut res = next.run(req).await;
411 res.extensions_mut().insert(crate::security::WantsEtag);
412 res
413 },
414 ))
415 .mark("etag")
416 }
417
418 pub fn without_csrf(self) -> Self {
422 self.mark("no-csrf")
423 }
424
425 pub fn offline(self) -> Self {
450 self.offline_with(crate::idempotency::Skew::default())
451 }
452
453 pub fn offline_with(self, skew: crate::idempotency::Skew) -> Self {
468 self.route_layer(from_fn(
469 move |req: Request, next: axum::middleware::Next| async move {
470 crate::idempotency::middleware(skew, req, next).await
471 },
472 ))
473 .mark("offline")
474 }
475
476 pub fn cors(self, origins: &[&str]) -> Self {
482 use axum::http::{HeaderName, HeaderValue, Method, header};
483 use tower_http::cors::{AllowOrigin, CorsLayer};
484
485 let origin = if origins.contains(&"*") {
486 AllowOrigin::any()
487 } else {
488 AllowOrigin::list(
489 origins
490 .iter()
491 .filter_map(|o| HeaderValue::from_str(o.trim_end_matches('/')).ok()),
492 )
493 };
494 let layer = CorsLayer::new()
495 .allow_origin(origin)
496 .allow_methods([
497 Method::GET,
498 Method::POST,
499 Method::PUT,
500 Method::PATCH,
501 Method::DELETE,
502 Method::OPTIONS,
503 ])
504 .allow_headers([
505 header::CONTENT_TYPE,
506 header::AUTHORIZATION,
507 header::ACCEPT,
508 HeaderName::from_static(crate::CSRF_HEADER),
509 ])
510 .max_age(std::time::Duration::from_secs(3600));
511 self.cors_layer(layer)
512 }
513
514 pub fn cors_layer(mut self, layer: tower_http::cors::CorsLayer) -> Self {
517 self.router = self.router.layer(layer);
520 self.mark("cors")
521 }
522
523 pub fn route_layer<L>(mut self, layer: L) -> Self
525 where
526 L: Layer<Route> + Clone + Send + Sync + 'static,
527 L::Service: Service<Request> + Clone + Send + Sync + 'static,
528 <L::Service as Service<Request>>::Response: IntoResponse + 'static,
529 <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
530 <L::Service as Service<Request>>::Future: Send + 'static,
531 {
532 self.router = self.router.route_layer(layer);
533 self
534 }
535
536 pub fn merge(mut self, other: impl Into<Routes>) -> Self {
538 let other = other.into();
539 self.router = self.router.merge(other.router);
540 self.names.extend(other.names);
541 self.listing.extend(other.listing);
542 self.domains.extend(other.domains);
543 assert!(
544 self.fallback.is_none() || other.fallback.is_none(),
545 "Routes::merge: both sides have a fallback"
546 );
547 self.fallback = self.fallback.or(other.fallback);
548 self.last_path = None;
549 self
550 }
551
552 pub fn fallback<H, T>(mut self, handler: H) -> Self
566 where
567 H: Handler<T, AppState>,
568 T: 'static,
569 {
570 assert!(
571 self.fallback.is_none(),
572 "Routes::fallback: these routes have a fallback already"
573 );
574 self.fallback = Some(routing::any(handler));
575 self
576 }
577
578 pub fn domain(mut self, pattern: &str, routes: impl Into<Routes>) -> Self {
604 self.domains.push((pattern.to_owned(), routes.into()));
605 self.last_path = None;
606 self
607 }
608
609 pub fn group(mut self, path: &str, name: &str, routes: impl Into<Routes>) -> Self {
634 assert!(
635 path.starts_with('/') && !path.ends_with('/'),
636 "Routes::group(\"{path}\", …): the prefix must start with `/` and not end with one"
637 );
638 let routes = routes.into();
639 assert!(
640 routes.domains.is_empty() && routes.fallback.is_none(),
641 "Routes::group(\"{path}\", …): put `domain` and `fallback` outside path groups"
642 );
643 let join = |inner: &str| {
644 if inner == "/" {
645 path.to_owned()
646 } else {
647 format!("{path}{inner}")
648 }
649 };
650 self.router = self.router.nest(path, routes.router);
651 self.names.extend(
652 routes
653 .names
654 .into_iter()
655 .map(|(route_name, route_path)| (format!("{name}{route_name}"), join(&route_path))),
656 );
657 self.listing
658 .extend(routes.listing.into_iter().map(|info| RouteInfo {
659 path: join(&info.path),
660 name: info.name.map(|route_name| format!("{name}{route_name}")),
661 ..info
662 }));
663 self.last_path = None;
664 self
665 }
666
667 pub(crate) fn into_parts(self) -> RouteParts {
668 RouteParts {
669 router: self.router,
670 names: self.names,
671 listing: self.listing,
672 fallback: self.fallback,
673 domains: self.domains,
674 }
675 }
676}
677
678impl From<Router<AppState>> for Routes {
679 fn from(router: Router<AppState>) -> Self {
680 Self {
681 router,
682 ..Self::default()
683 }
684 }
685}
686
687#[derive(Debug, Default)]
689pub struct RouteTable {
690 paths: HashMap<String, String>,
691 domains: HashMap<String, String>,
693 methods: HashMap<String, String>,
695}
696
697impl RouteTable {
698 pub(crate) fn insert(&mut self, name: String, path: String) -> anyhow::Result<()> {
699 if let Some(existing) = self.paths.get(&name) {
700 bail!("route name `{name}` is used for both `{existing}` and `{path}`");
701 }
702 self.paths.insert(name, path);
703 Ok(())
704 }
705
706 pub fn path(&self, name: &str) -> Option<&str> {
708 self.paths.get(name).map(String::as_str)
709 }
710
711 #[cfg_attr(not(test), allow(dead_code))]
713 pub(crate) fn names(&self) -> impl Iterator<Item = &str> {
714 self.paths.keys().map(String::as_str)
715 }
716
717 pub(crate) fn set_method(&mut self, name: &str, method: &str) {
719 self.methods.insert(name.to_owned(), method.to_owned());
720 }
721
722 pub(crate) fn set_domain(&mut self, name: &str, domain: &str) {
724 self.domains.insert(name.to_owned(), domain.to_owned());
725 }
726
727 pub(crate) fn name_of(
734 &self,
735 path: &str,
736 domain: Option<&str>,
737 method: Option<&str>,
738 ) -> Option<&str> {
739 let on_path = || {
740 self.paths
741 .iter()
742 .filter(move |(name, p)| {
743 p.as_str() == path && self.domains.get(*name).map(String::as_str) == domain
744 })
745 .map(|(name, _)| name.as_str())
746 };
747 let wanted = method.map(|m| if m == "HEAD" { "GET" } else { m });
748 let by_method = wanted.and_then(|wanted| {
749 on_path()
750 .filter(|name| {
751 self.methods.get(*name).is_some_and(|listed| {
752 listed == "*" || listed.split('|').any(|m| m == wanted)
753 })
754 })
755 .min()
756 });
757 by_method.or_else(|| on_path().min())
758 }
759
760 pub fn url(&self, name: &str, params: &[&dyn Display]) -> anyhow::Result<String> {
762 let pattern = self
763 .path(name)
764 .ok_or_else(|| anyhow!("route `{name}` is not defined"))?;
765 fill(pattern, params).map_err(|err| anyhow!("route `{name}`: {err}"))
766 }
767}
768
769fn fill(pattern: &str, params: &[&dyn Display]) -> anyhow::Result<String> {
770 let mut out = String::with_capacity(pattern.len());
771 let mut params = params.iter();
772 let mut rest = pattern;
773
774 while let Some(start) = rest.find('{') {
775 out.push_str(&rest[..start]);
776 let end = rest[start..]
777 .find('}')
778 .ok_or_else(|| anyhow!("unclosed `{{` in `{pattern}`"))?
779 + start;
780 let placeholder = &rest[start + 1..end];
781 let value = params
782 .next()
783 .ok_or_else(|| anyhow!("missing value for `{{{placeholder}}}`"))?
784 .to_string();
785 encode(&mut out, &value, placeholder.starts_with('*'));
786 rest = &rest[end + 1..];
787 }
788 out.push_str(rest);
789
790 if params.next().is_some() {
791 bail!("too many parameters for `{pattern}`");
792 }
793 Ok(out)
794}
795
796pub(crate) fn encode(out: &mut String, value: &str, keep_slashes: bool) {
797 for byte in value.bytes() {
798 match byte {
799 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
800 out.push(byte as char)
801 }
802 b'/' if keep_slashes => out.push('/'),
803 _ => {
804 let _ = write!(out, "%{byte:02X}");
805 }
806 }
807 }
808}
809
810#[cfg(test)]
811mod tests {
812 use super::*;
813
814 fn table() -> RouteTable {
815 let mut t = RouteTable::default();
816 t.insert("home".into(), "/".into()).unwrap();
817 t.insert("products.show".into(), "/products/{id}".into())
818 .unwrap();
819 t.insert("docs".into(), "/docs/{*path}".into()).unwrap();
820 t
821 }
822
823 #[test]
824 fn builds_urls() {
825 let t = table();
826 assert_eq!(t.url("home", &[]).unwrap(), "/");
827 assert_eq!(t.url("products.show", &[&42]).unwrap(), "/products/42");
828 assert_eq!(
829 t.url("products.show", &[&"a b/c"]).unwrap(),
830 "/products/a%20b%2Fc"
831 );
832 assert_eq!(
833 t.url("docs", &[&"guide/intro"]).unwrap(),
834 "/docs/guide/intro"
835 );
836 }
837
838 #[test]
839 fn rejects_bad_calls() {
840 let t = table();
841 assert!(t.url("missing", &[]).is_err());
842 assert!(t.url("products.show", &[]).is_err());
843 assert!(t.url("home", &[&1]).is_err());
844 }
845
846 #[test]
847 fn rejects_duplicate_names() {
848 let mut t = table();
849 assert!(t.insert("home".into(), "/home".into()).is_err());
850 }
851}
852
853#[derive(Default)]
856#[must_use = "a resource does nothing until given to Routes::resource"]
857pub struct Resource {
858 index: Option<MethodRouter<AppState>>,
859 create: Option<MethodRouter<AppState>>,
860 store: Option<MethodRouter<AppState>>,
861 show: Option<MethodRouter<AppState>>,
862 edit: Option<MethodRouter<AppState>>,
863 update: Option<MethodRouter<AppState>>,
864 destroy: Option<MethodRouter<AppState>>,
865}
866
867macro_rules! resource_action {
868 ($($action:ident => $router:expr),* $(,)?) => {$(
869 pub fn $action<H, T>(mut self, handler: H) -> Self
871 where
872 H: Handler<T, AppState>,
873 T: 'static,
874 {
875 let make: fn(H) -> MethodRouter<AppState> = $router;
876 self.$action = Some(make(handler));
877 self
878 }
879 )*};
880}
881
882impl Resource {
883 pub fn new() -> Self {
885 Self::default()
886 }
887
888 resource_action!(
889 index => routing::get,
890 create => routing::get,
891 store => routing::post,
892 show => routing::get,
893 edit => routing::get,
894 update => |h| routing::put(h.clone()).patch(h),
895 destroy => routing::delete,
896 );
897}
898
899pub(crate) fn route_name_matches(name: &str, pattern: &str) -> bool {
902 let mut parts = pattern.split('*');
903 let first = parts.next().unwrap_or_default();
904 let Some(mut rest) = name.strip_prefix(first) else {
905 return false;
906 };
907 let parts: Vec<&str> = parts.collect();
908 let Some((last, middle)) = parts.split_last() else {
909 return rest.is_empty(); };
911 for part in middle {
912 match rest.find(part) {
913 Some(at) => rest = &rest[at + part.len()..],
914 None => return false,
915 }
916 }
917 rest.ends_with(last)
918}
919
920#[derive(Debug, Clone)]
934pub struct CurrentRoute {
935 name: Option<String>,
936 path: Option<String>,
937}
938
939impl CurrentRoute {
940 pub fn name(&self) -> Option<&str> {
942 self.name.as_deref()
943 }
944
945 pub fn path(&self) -> Option<&str> {
947 self.path.as_deref()
948 }
949
950 pub fn is(&self, pattern: &str) -> bool {
953 self.name
954 .as_deref()
955 .is_some_and(|name| route_name_matches(name, pattern))
956 }
957
958 pub(crate) fn of(
959 method: &axum::http::Method,
960 extensions: &axum::http::Extensions,
961 state: &AppState,
962 ) -> Self {
963 let path = extensions
964 .get::<axum::extract::MatchedPath>()
965 .map(|p| p.as_str().to_owned());
966 let domain = extensions
967 .get::<crate::domain::MatchedDomain>()
968 .map(|d| &*d.0);
969 let name = path
970 .as_deref()
971 .and_then(|p| state.routes.name_of(p, domain, Some(method.as_str())))
972 .map(str::to_owned);
973 Self { name, path }
974 }
975}
976
977impl<S: Send + Sync> axum::extract::FromRequestParts<S> for CurrentRoute {
978 type Rejection = Infallible;
979
980 async fn from_request_parts(
981 parts: &mut axum::http::request::Parts,
982 _: &S,
983 ) -> Result<Self, Infallible> {
984 Ok(match parts.extensions.get::<AppState>() {
985 Some(state) => Self::of(&parts.method, &parts.extensions, state),
986 None => Self {
987 name: None,
988 path: None,
989 },
990 })
991 }
992}
993
994#[cfg(test)]
995mod route_name_tests {
996 use super::route_name_matches;
997
998 #[test]
999 fn patterns_match_like_laravel() {
1000 assert!(route_name_matches("admin.users.index", "admin.*"));
1001 assert!(route_name_matches("admin.users.index", "*.index"));
1002 assert!(route_name_matches("admin.users.index", "admin.*.index"));
1003 assert!(route_name_matches("products.show", "products.show"));
1004 assert!(!route_name_matches("products.show", "products"));
1005 assert!(!route_name_matches("shop.products.show", "products.*"));
1006 assert!(route_name_matches("anything", "*"));
1007 assert!(!route_name_matches("admin", "admin.*"));
1008 assert!(!route_name_matches("admin.users.index", "admin.*.posts.*"));
1010 assert!(route_name_matches(
1011 "admin.users.posts.edit",
1012 "admin.*.posts.*"
1013 ));
1014 }
1015
1016 #[tokio::test]
1019 async fn current_route_without_the_app_is_none() {
1020 use axum::extract::FromRequestParts;
1021 let (mut parts, ()) = axum::http::Request::builder()
1022 .uri("/x")
1023 .body(())
1024 .unwrap()
1025 .into_parts();
1026 let current = super::CurrentRoute::from_request_parts(&mut parts, &())
1027 .await
1028 .unwrap();
1029 assert_eq!(current.name(), None);
1030 }
1031}
1032
1033fn redirect_with(status: axum::http::StatusCode, to: &str) -> axum::response::Response {
1035 match axum::http::HeaderValue::from_str(to) {
1036 Ok(location) => (status, [(axum::http::header::LOCATION, location)]).into_response(),
1037 Err(_) => axum::http::StatusCode::INTERNAL_SERVER_ERROR.into_response(),
1038 }
1039}