1use std::sync::Arc;
46use std::time::Duration;
47
48use axum::extract::State;
49use axum::http::{StatusCode, Uri};
50use axum::response::{IntoResponse, Redirect, Response};
51use axum::routing::get;
52use axum::Router;
53use rustango::cache::BoxedCache;
54use rustango::cache_page::CachePageLayer;
55use rustango::extractors::Tenant;
56use tera::Tera;
57
58use crate::locale_mode::{resolve_request_locale, LocaleMode};
59use crate::render::{render_negotiated, render_with_route};
60use crate::resolver::{resolve_path, resolve_routable};
61
62#[derive(Clone)]
68pub(crate) struct PublicState {
69 pub(crate) tera: Arc<Tera>,
70 pub(crate) url_prefix: String,
71 locale_mode: LocaleMode,
72 pub(crate) mailer: Option<Arc<dyn rustango::email::Mailer>>,
76 pub(crate) mailer_from: Arc<String>,
77 pub(crate) fragment_cache: Option<(BoxedCache, Duration)>,
82 pub(crate) tenant_templates: Option<Arc<crate::tenant_templates::TenantTemplates>>,
86}
87
88impl PublicState {
89 fn new(tera: Arc<Tera>, url_prefix: String) -> Self {
90 Self {
91 tera,
92 url_prefix,
93 locale_mode: LocaleMode::default(),
94 mailer: None,
95 mailer_from: Arc::new(String::new()),
96 fragment_cache: None,
97 tenant_templates: None,
98 }
99 }
100
101 pub(crate) async fn tera_for(&self, slug: &str) -> Arc<Tera> {
108 let Some(tt) = self.tenant_templates.as_ref() else {
109 return Arc::clone(&self.tera);
110 };
111 if let Some(cached) = tt.cached(slug) {
112 return cached;
113 }
114 let (tt, owned) = (Arc::clone(tt), slug.to_owned());
115 rustango::__private_runtime::tokio::task::spawn_blocking(move || tt.for_tenant(&owned))
116 .await
117 .unwrap_or_else(|_| Arc::clone(&self.tera))
118 }
119 fn with_fragment_cache(mut self, cache: BoxedCache, ttl: Duration) -> Self {
120 self.fragment_cache = Some((cache, ttl));
121 self
122 }
123 fn with_locale_mode(mut self, mode: LocaleMode) -> Self {
124 self.locale_mode = mode;
125 self
126 }
127 pub(crate) fn locale_mode(&self) -> LocaleMode {
130 self.locale_mode
131 }
132 fn with_mailer(
133 mut self,
134 mailer: Arc<dyn rustango::email::Mailer>,
135 from: impl Into<String>,
136 ) -> Self {
137 self.mailer = Some(mailer);
138 self.mailer_from = Arc::new(from.into());
139 self
140 }
141}
142
143fn apply_cache_layer(router: Router, cache: BoxedCache, ttl: Duration) -> Router {
159 router
160 .layer(
161 CachePageLayer::new(cache)
162 .timeout(ttl)
163 .key_prefix("rcms:page")
164 .vary_on(["accept-language", "x-rcms-locale", "x-rcms-accept"]),
165 )
166 .layer(axum::middleware::map_request(inject_locale_cookie_header))
169 .layer(axum::middleware::map_request(inject_accept_kind_header))
170}
171
172async fn inject_accept_kind_header(mut req: axum::extract::Request) -> axum::extract::Request {
189 let accept = crate::page_view::parse_accept(
190 req.headers()
191 .get(axum::http::header::ACCEPT)
192 .and_then(|v| v.to_str().ok()),
193 );
194 if accept == crate::page_view::Accept::Json {
195 req.headers_mut().insert(
196 axum::http::HeaderName::from_static("x-rcms-accept"),
197 axum::http::HeaderValue::from_static("json"),
198 );
199 }
200 req
201}
202
203async fn inject_locale_cookie_header(mut req: axum::extract::Request) -> axum::extract::Request {
208 let code = crate::locale_mode::locale_cookie_value(
209 req.headers()
210 .get(axum::http::header::COOKIE)
211 .and_then(|v| v.to_str().ok()),
212 );
213 if let Some(code) = code {
214 if let Ok(hv) = axum::http::HeaderValue::from_str(&code) {
215 req.headers_mut()
216 .insert(axum::http::HeaderName::from_static("x-rcms-locale"), hv);
217 }
218 }
219 req
220}
221
222pub struct PublicRouter {
240 tera: Arc<Tera>,
241 prefix: String,
242 cache: Option<(BoxedCache, Duration)>,
243 locale_mode: LocaleMode,
244 mailer: Option<(Arc<dyn rustango::email::Mailer>, String)>,
245 static_dirs: Vec<(String, std::path::PathBuf)>,
249 static_files: Vec<(String, &'static [u8], &'static str)>,
252 tenant_templates: Option<Arc<crate::tenant_templates::TenantTemplates>>,
255}
256
257impl PublicRouter {
258 #[must_use]
261 pub fn new(tera: Arc<Tera>) -> Self {
262 Self {
263 tera,
264 prefix: String::new(),
265 cache: None,
266 locale_mode: LocaleMode::default(),
267 mailer: None,
268 static_dirs: Vec::new(),
269 static_files: Vec::new(),
270 tenant_templates: None,
271 }
272 }
273
274 #[must_use]
290 pub fn static_dir(
291 mut self,
292 url_prefix: impl Into<String>,
293 fs_root: impl Into<std::path::PathBuf>,
294 ) -> Self {
295 self.static_dirs.push((url_prefix.into(), fs_root.into()));
296 self
297 }
298
299 #[must_use]
304 pub fn static_file(
305 mut self,
306 url_path: impl Into<String>,
307 bytes: &'static [u8],
308 content_type: &'static str,
309 ) -> Self {
310 self.static_files
311 .push((url_path.into(), bytes, content_type));
312 self
313 }
314
315 #[must_use]
320 pub fn with_form_mailer(
321 mut self,
322 mailer: Arc<dyn rustango::email::Mailer>,
323 from_addr: impl Into<String>,
324 ) -> Self {
325 self.mailer = Some((mailer, from_addr.into()));
326 self
327 }
328
329 #[must_use]
332 pub fn at(mut self, prefix: impl Into<String>) -> Self {
333 self.prefix = prefix.into();
334 self
335 }
336
337 #[must_use]
345 pub fn cached(mut self, cache: BoxedCache, ttl: Duration) -> Self {
346 self.cache = Some((cache, ttl));
347 self
348 }
349
350 #[must_use]
353 pub fn locale_mode(mut self, mode: LocaleMode) -> Self {
354 self.locale_mode = mode;
355 self
356 }
357
358 #[must_use]
379 pub fn tenant_templates(mut self, tt: crate::tenant_templates::TenantTemplates) -> Self {
380 self.tenant_templates = Some(Arc::new(tt));
381 self
382 }
383
384 #[must_use]
390 pub fn tenant_templates_shared(
391 mut self,
392 tt: Arc<crate::tenant_templates::TenantTemplates>,
393 ) -> Self {
394 self.tenant_templates = Some(tt);
395 self
396 }
397
398 #[must_use]
400 pub fn build(self) -> Router {
401 let mut state =
402 PublicState::new(self.tera, self.prefix.clone()).with_locale_mode(self.locale_mode);
403 state.tenant_templates = self.tenant_templates;
404 if let Some((mailer, from)) = self.mailer {
405 state = state.with_mailer(mailer, from);
406 }
407 if let Some((cache, ttl)) = &self.cache {
411 state = state.with_fragment_cache(cache.clone(), *ttl);
412 }
413 let cms_router = if self.prefix.is_empty() {
414 fallback_router(state)
415 } else {
416 explicit_router(&self.prefix, state)
417 };
418 let cms_router = if let Some((cache, ttl)) = self.cache {
419 apply_cache_layer(cms_router, cache, ttl)
420 } else {
421 cms_router
422 };
423
424 let mut router = Router::new();
430 for (url_prefix, fs_root) in self.static_dirs {
431 let trimmed = url_prefix.trim_end_matches('/').to_owned();
432 let pattern = format!("{trimmed}/{{*path}}");
433 let root = Arc::new(fs_root);
434 router = router.route(
435 &pattern,
436 axum::routing::get({
437 let root = root.clone();
438 move |path: axum::extract::Path<String>| {
439 let root = root.clone();
440 async move {
443 rustango::__private_runtime::tokio::task::spawn_blocking(move || {
444 serve_static_path(&root, &path.0)
445 })
446 .await
447 .unwrap_or_else(|_| not_found())
448 }
449 }
450 }),
451 );
452 }
453 for (url_path, bytes, ct) in self.static_files {
454 router = router.route(
455 &url_path,
456 axum::routing::get(move || async move { serve_static_bytes(bytes, ct) }),
457 );
458 }
459 router.merge(cms_router)
460 }
461}
462
463fn serve_static_path(fs_root: &std::path::Path, requested: &str) -> Response {
467 if requested.is_empty() || requested.contains('\0') {
472 return not_found();
473 }
474 for seg in requested.split('/') {
475 if seg == ".." || seg.starts_with('/') {
476 return not_found();
477 }
478 }
479 let candidate = fs_root.join(requested);
480 let canon_root = match fs_root.canonicalize() {
484 Ok(p) => p,
485 Err(_) => return not_found(),
486 };
487 let canon = match candidate.canonicalize() {
488 Ok(p) => p,
489 Err(_) => return not_found(),
490 };
491 if !canon.starts_with(&canon_root) {
492 return not_found();
493 }
494 let bytes = match std::fs::read(&canon) {
495 Ok(b) => b,
496 Err(_) => return not_found(),
497 };
498 let ct = mime_guess::from_path(&canon)
499 .first_or_octet_stream()
500 .essence_str()
501 .to_owned();
502 static_response(bytes, &ct)
503}
504
505fn serve_static_bytes(bytes: &'static [u8], content_type: &'static str) -> Response {
506 static_response(bytes.to_vec(), content_type)
507}
508
509fn static_response(bytes: Vec<u8>, content_type: &str) -> Response {
510 use axum::http::header;
511 (
515 axum::http::StatusCode::OK,
516 [
517 (
518 header::CONTENT_TYPE,
519 axum::http::HeaderValue::from_str(content_type).unwrap_or_else(|_| {
520 axum::http::HeaderValue::from_static("application/octet-stream")
521 }),
522 ),
523 (
524 header::CACHE_CONTROL,
525 axum::http::HeaderValue::from_static("public, max-age=3600"),
526 ),
527 ],
528 bytes,
529 )
530 .into_response()
531}
532
533fn not_found() -> Response {
534 (axum::http::StatusCode::NOT_FOUND, "Not Found").into_response()
535}
536
537pub fn router(tera: Arc<Tera>) -> Router {
541 fallback_router(PublicState::new(tera, String::new()))
542}
543
544pub fn router_cached(tera: Arc<Tera>, cache: BoxedCache, ttl: Duration) -> Router {
549 apply_cache_layer(
550 fallback_router(PublicState::new(tera, String::new())),
551 cache,
552 ttl,
553 )
554}
555
556pub fn router_at(prefix: &str, tera: Arc<Tera>) -> Router {
570 explicit_router(prefix, PublicState::new(tera, prefix.to_owned()))
571}
572
573pub fn router_at_cached(prefix: &str, tera: Arc<Tera>, cache: BoxedCache, ttl: Duration) -> Router {
576 apply_cache_layer(
577 explicit_router(prefix, PublicState::new(tera, prefix.to_owned())),
578 cache,
579 ttl,
580 )
581}
582
583fn fallback_router(state: PublicState) -> Router {
584 crate::perf::instrument(fallback_router_inner(state))
585}
586
587fn fallback_router_inner(state: PublicState) -> Router {
588 Router::new()
589 .route("/sitemap.xml", get(crate::sitemap::handle_sitemap))
590 .route("/robots.txt", get(crate::robots::handle_robots))
595 .route("/sitemap/{n}", get(crate::sitemap::handle_sitemap_shard))
597 .route("/feed/{kind}/rss.xml", get(crate::feed::handle_feed_rss))
598 .route("/feed/{kind}/atom.xml", get(crate::feed::handle_feed_atom))
599 .route(
601 "/__cms-view-password",
602 get(handle_view_password_form).post(handle_view_password_submit),
603 )
604 .route(
606 "/forms/submit/{form_id}",
607 axum::routing::post(crate::forms::submit::handle_form_submit)
608 .layer(axum::extract::DefaultBodyLimit::max(crate::forms::submit::MAX_SUBMISSION_BYTES)),
609 )
610 .route("/forms/runtime.js", get(serve_form_runtime_js))
612 .route("/forms/forms.css", get(serve_form_css))
614 .route(
616 crate::analytics::COLLECT_PATH,
617 axum::routing::post(crate::analytics::collect::handle_collect),
618 )
619 .route(
620 crate::analytics::WS_PATH,
621 get(crate::analytics::ws::handle_ws),
622 )
623 .route(
624 crate::analytics::BEACON_JS_PATH,
625 get(crate::analytics::serve_beacon_js),
626 )
627 .fallback(get(handle_page_request))
628 .layer(axum::middleware::from_fn(crate::seed::lazy_seed_layer))
630 .with_state(state)
631}
632
633async fn serve_form_runtime_js() -> impl IntoResponse {
635 serve_static_bytes(include_str!("forms/runtime.js").as_bytes(), "text/javascript; charset=utf-8")
637}
638
639async fn serve_form_css() -> impl IntoResponse {
641 serve_static_bytes(include_str!("forms/forms.css").as_bytes(), "text/css; charset=utf-8")
642}
643
644fn explicit_router(prefix: &str, state: PublicState) -> Router {
645 let inner = Router::new()
646 .route("/sitemap.xml", get(crate::sitemap::handle_sitemap))
647 .route("/robots.txt", get(crate::robots::handle_robots))
652 .route("/sitemap/{n}", get(crate::sitemap::handle_sitemap_shard))
654 .route("/feed/{kind}/rss.xml", get(crate::feed::handle_feed_rss))
655 .route("/feed/{kind}/atom.xml", get(crate::feed::handle_feed_atom))
656 .route(
657 "/__cms-view-password",
658 get(handle_view_password_form).post(handle_view_password_submit),
659 )
660 .route(
662 "/forms/submit/{form_id}",
663 axum::routing::post(crate::forms::submit::handle_form_submit)
664 .layer(axum::extract::DefaultBodyLimit::max(crate::forms::submit::MAX_SUBMISSION_BYTES)),
665 )
666 .route("/forms/runtime.js", get(serve_form_runtime_js))
668 .route("/forms/forms.css", get(serve_form_css))
669 .route(
671 crate::analytics::COLLECT_PATH,
672 axum::routing::post(crate::analytics::collect::handle_collect),
673 )
674 .route(
675 crate::analytics::WS_PATH,
676 get(crate::analytics::ws::handle_ws),
677 )
678 .route(
679 crate::analytics::BEACON_JS_PATH,
680 get(crate::analytics::serve_beacon_js),
681 )
682 .route("/", get(handle_page_request))
683 .route("/{*path}", get(handle_page_request))
684 .layer(axum::middleware::from_fn(crate::seed::lazy_seed_layer))
685 .with_state(state);
686 if prefix.is_empty() {
687 return inner;
688 }
689 let trailing = format!("{prefix}/");
690 let bare = prefix.to_owned();
691 Router::new().nest(prefix, inner).route(
692 &trailing,
693 get(move || {
694 let bare = bare.clone();
695 async move { Redirect::permanent(&bare) }
696 }),
697 )
698}
699
700pub(crate) fn host_header(headers: &axum::http::HeaderMap) -> &str {
702 headers
703 .get(axum::http::header::HOST)
704 .and_then(|v| v.to_str().ok())
705 .map_or("", |h| h.split(':').next().unwrap_or(""))
706}
707
708fn hook_ctx<'a>(tenant: &'a Tenant, viewer: Option<&rustango::tenancy::auth::User>) -> crate::hooks::HookCtx<'a> {
710 crate::hooks::HookCtx::new(tenant.pool(), &tenant.org.slug, viewer.and_then(|u| u.id.get().copied()))
711}
712
713async fn handle_page_request(
714 tenant: Tenant,
715 State(state): State<PublicState>,
716 rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
717 rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
718 headers: axum::http::HeaderMap,
719 uri: Uri,
720) -> Response {
721 let admin = if member.is_none() { session_user.as_ref() } else { None };
724 let inspect = admin.is_some_and(crate::template_inspector::wanted);
725 let bar = admin.map(|_| crate::admin_bar::Labels {
726 edit: crate::admin::tr(&headers, "Edit this page"),
727 admin: crate::admin::tr(&headers, "Admin"),
728 hide: crate::admin::tr(&headers, "Show or hide the admin bar"),
729 templates: crate::admin::tr(&headers, "Templates"),
730 });
731 crate::admin_bar::scope(
732 bar,
733 crate::template_inspector::scope(inspect, serve_page(tenant, state, session_user, member, headers, uri)),
734 )
735 .await
736}
737
738async fn serve_page(
739 tenant: Tenant,
740 state: PublicState,
741 session_user: Option<rustango::tenancy::auth::User>,
742 member: Option<rustango::tenancy::auth::User>,
743 headers: axum::http::HeaderMap,
744 uri: Uri,
745) -> Response {
746 let viewer = member.as_ref().or(session_user.as_ref());
752 let raw_path = uri.path();
753 let _perf_t = crate::perf::start();
758 if let Some(resp) = crate::redirect::serve_override(
759 &tenant,
760 state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl)),
761 raw_path,
762 uri.query(),
763 )
764 .await
765 {
766 crate::perf::mark("redirect_rules", _perf_t);
767 return resp;
768 }
769 crate::perf::mark("redirect_rules", _perf_t);
770 let accept_language = headers
775 .get(axum::http::header::ACCEPT_LANGUAGE)
776 .and_then(|v| v.to_str().ok());
777 let accept = crate::page_view::parse_accept(
781 headers
782 .get(axum::http::header::ACCEPT)
783 .and_then(|v| v.to_str().ok()),
784 );
785 let cookie_code = crate::locale_mode::locale_cookie_value(
788 headers
789 .get(axum::http::header::COOKIE)
790 .and_then(|v| v.to_str().ok()),
791 );
792 let _perf_t = crate::perf::start();
793 let request_locale = resolve_request_locale(
794 tenant.pool(),
795 state.locale_mode,
796 raw_path,
797 uri.query(),
798 cookie_code.as_deref(),
799 accept_language,
800 )
801 .await;
802 crate::perf::mark("locale", _perf_t);
803 let locale_code = request_locale.code.clone();
804 let locale_explicit = request_locale.explicit;
805 let lookup_path = request_locale.stripped_path;
806
807 let _perf_t = crate::perf::start();
811 let site_prefix = crate::site::prefix_for_host(tenant.pool(), host_header(&headers))
812 .await
813 .unwrap_or_default();
814 crate::perf::mark("site", _perf_t);
815 let lookup_path = crate::site::to_lookup_path(&site_prefix, &lookup_path);
818
819 let _perf_t = crate::perf::start();
820 let _resolved = resolve_path(&tenant, &lookup_path).await;
821 crate::perf::mark("resolve_path", _perf_t);
822 match _resolved {
823 Ok(Some(page)) => {
824 let _perf_t = crate::perf::start();
829 let _blocked =
830 crate::view_restriction_guard::enforce(&tenant, &page, viewer, &headers, raw_path)
831 .await;
832 crate::perf::mark("view_restriction", _perf_t);
833 if let Some(blocked) = _blocked {
834 return styled_denial(&tenant, &state, blocked, locale_code.as_deref()).await;
835 }
836 if let Some(resp) = crate::hooks::fire_before_serve_page(hook_ctx(&tenant, viewer), &page, &headers).await {
839 return resp;
840 }
841 let _perf_t = crate::perf::start();
847 let tera = state.tera_for(&tenant.org.slug).await;
851 let _switcher =
855 install_locale_switcher(&tenant, &state, &page, locale_code.as_deref()).await;
856 let _origin = crate::meta_tags::stash_site_origin(crate::sitemap::base_url(&headers));
859 let resp = render_negotiated(
860 &tenant,
861 &tera,
862 &page,
863 &state.url_prefix,
864 &site_prefix,
865 locale_code.as_deref(),
866 viewer,
867 accept,
868 state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl)),
869 )
870 .await;
871 crate::perf::mark("render", _perf_t);
872 let resp = if resp.status().is_server_error() {
876 crate::error_pages::respond(&tenant, &state, resp.status(), locale_code.as_deref())
877 .await
878 } else {
879 resp
880 };
881 persist_locale(resp, locale_explicit, locale_code.as_deref())
882 }
883 Ok(None) => {
884 match resolve_routable(&tenant, &lookup_path).await {
890 Ok(Some((page, route_match))) => {
891 if let Some(blocked) = crate::view_restriction_guard::enforce(
892 &tenant, &page, viewer, &headers, raw_path,
893 )
894 .await
895 {
896 return styled_denial(&tenant, &state, blocked, locale_code.as_deref()).await;
897 }
898 if let Some(resp) = crate::hooks::fire_before_serve_page(hook_ctx(&tenant, viewer), &page, &headers).await {
899 return resp;
900 }
901 let tera = state.tera_for(&tenant.org.slug).await;
902 let _switcher =
903 install_locale_switcher(&tenant, &state, &page, locale_code.as_deref())
904 .await;
905 let _origin =
906 crate::meta_tags::stash_site_origin(crate::sitemap::base_url(&headers));
907 let resp = render_with_route(
908 &tenant,
909 &tera,
910 &page,
911 &state.url_prefix,
912 &site_prefix,
913 locale_code.as_deref(),
914 viewer,
915 &route_match,
916 accept,
917 state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl)),
918 )
919 .await;
920 let resp = if resp.status().is_server_error() || resp.status() == StatusCode::NOT_FOUND {
923 crate::error_pages::respond(
924 &tenant,
925 &state,
926 resp.status(),
927 locale_code.as_deref(),
928 )
929 .await
930 } else {
931 resp
932 };
933 return persist_locale(resp, locale_explicit, locale_code.as_deref());
934 }
935 Ok(None) => {}
936 Err(e) => {
937 tracing::error!(path = %raw_path, error = %e, "resolve_routable failed");
938 }
939 }
940 fallthrough_to_redirect(
941 &tenant,
942 &state,
943 raw_path,
944 uri.query(),
945 locale_code.as_deref(),
946 )
947 .await
948 }
949 Err(e) => {
950 tracing::error!(path = %raw_path, error = %e, "resolve_path failed");
951 crate::error_pages::respond(
952 &tenant,
953 &state,
954 StatusCode::INTERNAL_SERVER_ERROR,
955 locale_code.as_deref(),
956 )
957 .await
958 }
959 }
960}
961
962fn persist_locale(mut resp: Response, explicit: bool, code: Option<&str>) -> Response {
970 use axum::http::header::{HeaderValue, SET_COOKIE, VARY};
971 resp.headers_mut()
972 .append(VARY, HeaderValue::from_static("Cookie"));
973 if explicit {
974 if let Some(code) = code {
975 let cookie = format!(
976 "{}={code}; Path=/; SameSite=Lax; HttpOnly; Max-Age=31536000",
977 crate::locale_mode::LOCALE_COOKIE
978 );
979 if let Ok(hv) = HeaderValue::from_str(&cookie) {
980 resp.headers_mut().append(SET_COOKIE, hv);
981 }
982 }
983 }
984 resp
985}
986
987async fn styled_denial(
991 tenant: &Tenant,
992 state: &PublicState,
993 blocked: Response,
994 locale_code: Option<&str>,
995) -> Response {
996 if blocked.status() == StatusCode::FORBIDDEN {
997 crate::error_pages::respond(tenant, state, StatusCode::FORBIDDEN, locale_code).await
998 } else {
999 blocked
1000 }
1001}
1002
1003pub(crate) async fn install_locale_switcher(
1014 tenant: &Tenant,
1015 state: &PublicState,
1016 page: &crate::page::Page,
1017 current_code: Option<&str>,
1018) -> crate::language_switcher::PendingGuard {
1019 use rustango::core::Column as _;
1020 use rustango::sql::FetcherPool as _;
1021 let locales: Vec<crate::locale::Locale> = crate::locale::Locale::objects()
1022 .where_(crate::locale::Locale::active.eq(true))
1023 .order_by(&[("sort_order", false)])
1024 .fetch(tenant.pool())
1025 .await
1026 .unwrap_or_default();
1027 let entries = crate::language_switcher::build(
1028 &locales,
1029 &state.url_prefix,
1030 &page.url_path,
1031 state.locale_mode,
1032 current_code,
1033 );
1034 crate::language_switcher::stash_pending(entries)
1035}
1036
1037async fn fallthrough_to_redirect(
1048 tenant: &Tenant,
1049 state: &PublicState,
1050 raw_path: &str,
1051 query: Option<&str>,
1052 locale_code: Option<&str>,
1053) -> Response {
1054 match crate::redirect::find_for_path(tenant.pool(), raw_path).await {
1055 Ok(Some(row)) => {
1056 let to = crate::redirect::resolve_destination(tenant.pool(), &row).await;
1059 let rule = rustango::redirects::RedirectRule {
1060 to,
1061 permanent: row.is_permanent,
1062 };
1063 let resp = rustango::redirects::build_redirect_response(&rule, query);
1064 crate::redirect::record_hit(
1067 tenant.pool(),
1068 &tenant.org.slug,
1069 row.id.get().copied().unwrap_or_default(),
1070 );
1071 resp
1072 }
1073 Ok(None) => {
1077 let cache = state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl));
1078 if let Some(resp) =
1079 crate::redirect::serve_wildcard(tenant, cache, raw_path, query).await
1080 {
1081 return resp;
1082 }
1083 if raw_path.trim_matches('/').is_empty() && crate::error_pages::site_is_empty(tenant.pool()).await {
1084 return crate::error_pages::empty_site_response();
1085 }
1086 crate::error_pages::respond(tenant, state, StatusCode::NOT_FOUND, locale_code).await
1087 }
1088 Err(e) => {
1089 tracing::warn!(path = %raw_path, error = %e, "redirect lookup failed");
1090 crate::error_pages::respond(tenant, state, StatusCode::NOT_FOUND, locale_code).await
1091 }
1092 }
1093}
1094
1095#[derive(Debug, serde::Deserialize)]
1100struct PasswordPromptQuery {
1101 page: i64,
1102 #[serde(default)]
1103 next: Option<String>,
1104 #[serde(default)]
1105 error: Option<String>,
1106}
1107
1108#[derive(Debug, serde::Deserialize)]
1109struct PasswordSubmitForm {
1110 page: i64,
1111 password: String,
1112 #[serde(default)]
1113 next: Option<String>,
1114}
1115
1116async fn handle_view_password_form(
1117 tenant: Tenant,
1118 State(state): State<PublicState>,
1119 headers: axum::http::HeaderMap,
1120 axum::extract::Query(q): axum::extract::Query<PasswordPromptQuery>,
1121) -> Response {
1122 use rustango::core::Column as _;
1123 use rustango::sql::FetcherPool as _;
1124 let _ = &tenant;
1125 let page_rows: Vec<crate::page::Page> = crate::page::Page::objects()
1126 .where_(crate::page::Page::id.eq(q.page))
1127 .fetch(tenant.pool())
1128 .await
1129 .unwrap_or_default();
1130 let title = page_rows
1131 .first()
1132 .map(|p| p.title.clone())
1133 .unwrap_or_else(|| "Protected page".to_owned());
1134 let next = q.next.clone().unwrap_or_else(|| "/".to_owned());
1135 let error_msg = q.error.as_deref().unwrap_or("");
1136 let mut ctx = tera::Context::new();
1137 ctx.insert("page_id", &q.page);
1138 ctx.insert("page_title", &title);
1139 ctx.insert("next_path", &next);
1140 ctx.insert("error_message", &error_msg);
1141 let (csrf_token, csrf_cookie) =
1144 rustango::forms::csrf::ensure_token(&headers, rustango::forms::csrf::CSRF_COOKIE);
1145 ctx.insert("csrf_token", &csrf_token);
1146 match state.tera.render("rcms/view_password.html", &ctx) {
1147 Ok(body) => {
1148 let mut resp = axum::response::Html(body).into_response();
1149 if let Some(v) = csrf_cookie.and_then(|c| axum::http::HeaderValue::from_str(&c).ok()) {
1150 resp.headers_mut().append(axum::http::header::SET_COOKIE, v);
1151 }
1152 resp
1153 }
1154 Err(e) => {
1155 tracing::error!(error = %e, "view-password template render failed");
1156 (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
1157 }
1158 }
1159}
1160
1161async fn handle_view_password_submit(
1162 tenant: Tenant,
1163 axum::extract::Form(form): axum::extract::Form<PasswordSubmitForm>,
1164) -> Response {
1165 let Some(restriction) = crate::view_restriction::direct_for_page(tenant.pool(), form.page)
1166 .await
1167 .unwrap_or(None)
1168 .filter(|r| r.kind == crate::view_restriction::RestrictionKind::Password.as_str())
1169 else {
1170 return (
1171 StatusCode::BAD_REQUEST,
1172 "no password restriction on this page",
1173 )
1174 .into_response();
1175 };
1176 let _ = &tenant;
1177 let _ = &restriction.password_hash;
1178 let ok =
1180 crate::passwords::verify(&form.password, &restriction.password_hash).await.unwrap_or(false);
1181 let next = form
1183 .next
1184 .as_deref()
1185 .and_then(rustango::auth_decorators::safe_next)
1186 .unwrap_or_else(|| "/".to_owned());
1187 if !ok {
1188 let next_enc = crate::view_restriction_guard::url_encode_path(&next);
1189 return Redirect::to(&format!(
1190 "/__cms-view-password?page={}&next={next_enc}&error=Wrong+password",
1191 form.page
1192 ))
1193 .into_response();
1194 }
1195 let cookie =
1198 crate::view_restriction_guard::grant_cookie(&tenant.org.slug, &restriction, form.page);
1199 let mut response = Redirect::to(&next).into_response();
1200 if let Ok(hv) = axum::http::HeaderValue::from_str(&cookie) {
1201 response
1202 .headers_mut()
1203 .append(axum::http::header::SET_COOKIE, hv);
1204 }
1205 response
1206}
1207
1208#[cfg(test)]
1209mod static_serve_tests {
1210 use super::*;
1211 use std::fs;
1212 use std::path::PathBuf;
1213
1214 fn tempdir(name: &str) -> PathBuf {
1218 let mut p = std::env::temp_dir();
1219 p.push(format!("rustango_cms_static_{name}_{}", std::process::id()));
1220 let _ = fs::remove_dir_all(&p);
1221 fs::create_dir_all(&p).expect("create tempdir");
1222 p
1223 }
1224
1225 #[test]
1226 fn serves_existing_file_with_guessed_mime() {
1227 let dir = tempdir("hit");
1228 fs::write(dir.join("styles.css"), b"body{color:red}").unwrap();
1229 let resp = serve_static_path(&dir, "styles.css");
1230 assert_eq!(resp.status(), axum::http::StatusCode::OK);
1231 let ct = resp
1232 .headers()
1233 .get(axum::http::header::CONTENT_TYPE)
1234 .unwrap()
1235 .to_str()
1236 .unwrap();
1237 assert!(ct.starts_with("text/css"), "got `{ct}`");
1238 let cc = resp
1239 .headers()
1240 .get(axum::http::header::CACHE_CONTROL)
1241 .unwrap()
1242 .to_str()
1243 .unwrap();
1244 assert!(cc.contains("max-age=3600"));
1245 }
1246
1247 #[test]
1248 fn rejects_dotdot_traversal_in_segment() {
1249 let dir = tempdir("trav");
1250 fs::write(dir.join("ok.txt"), b"in-root").unwrap();
1251 let resp = serve_static_path(&dir, "../etc/passwd");
1253 assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1254 }
1255
1256 #[test]
1257 fn rejects_absolute_segment() {
1258 let dir = tempdir("abs");
1259 let resp = serve_static_path(&dir, "/etc/passwd");
1261 assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1262 }
1263
1264 #[test]
1265 fn rejects_null_byte_in_path() {
1266 let dir = tempdir("null");
1267 let resp = serve_static_path(&dir, "ok\0.txt");
1268 assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1269 }
1270
1271 #[test]
1272 fn missing_file_is_404_not_500() {
1273 let dir = tempdir("miss");
1274 let resp = serve_static_path(&dir, "does-not-exist.css");
1275 assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1276 }
1277
1278 #[test]
1279 fn serves_static_bytes_with_supplied_content_type() {
1280 let resp = serve_static_bytes(b"<svg/>", "image/svg+xml");
1281 assert_eq!(resp.status(), axum::http::StatusCode::OK);
1282 assert_eq!(
1283 resp.headers()
1284 .get(axum::http::header::CONTENT_TYPE)
1285 .and_then(|v| v.to_str().ok()),
1286 Some("image/svg+xml"),
1287 );
1288 }
1289
1290 #[test]
1291 fn nested_subdir_is_served() {
1292 let dir = tempdir("nested");
1293 fs::create_dir_all(dir.join("css/sub")).unwrap();
1294 fs::write(dir.join("css/sub/x.css"), b"x{}").unwrap();
1295 let resp = serve_static_path(&dir, "css/sub/x.css");
1296 assert_eq!(resp.status(), axum::http::StatusCode::OK);
1297 }
1298
1299 #[test]
1300 fn empty_path_is_404() {
1301 let dir = tempdir("empty");
1302 let resp = serve_static_path(&dir, "");
1303 assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1304 }
1305}
1306
1307#[cfg(test)]
1308mod accept_cache_key_tests {
1309 use super::*;
1310 use axum::http::{HeaderValue, Request};
1311
1312 fn req_with_accept(accept: Option<&str>) -> axum::extract::Request {
1313 let mut b = Request::builder().uri("/some-page");
1314 if let Some(a) = accept {
1315 b = b.header(
1316 axum::http::header::ACCEPT,
1317 HeaderValue::from_str(a).unwrap(),
1318 );
1319 }
1320 b.body(axum::body::Body::empty()).unwrap()
1321 }
1322
1323 async fn stamped(accept: Option<&str>) -> Option<String> {
1324 let req = inject_accept_kind_header(req_with_accept(accept)).await;
1325 req.headers()
1326 .get("x-rcms-accept")
1327 .and_then(|v| v.to_str().ok())
1328 .map(str::to_owned)
1329 }
1330
1331 #[tokio::test]
1335 async fn only_an_explicit_json_preference_changes_the_cache_key() {
1336 assert_eq!(
1337 stamped(Some("application/json")).await.as_deref(),
1338 Some("json")
1339 );
1340 assert_eq!(
1341 stamped(Some("application/json, text/plain, */*"))
1342 .await
1343 .as_deref(),
1344 Some("json")
1345 );
1346
1347 let chrome = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,\
1349 image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7";
1350 assert_eq!(stamped(Some(chrome)).await, None);
1351 assert_eq!(stamped(Some("*/*")).await, None);
1352 assert_eq!(stamped(None).await, None);
1353 assert_eq!(
1355 stamped(Some("application/json;q=0.1, text/html")).await,
1356 None
1357 );
1358 assert_eq!(stamped(Some("application/json;q=0")).await, None);
1360 }
1361
1362 #[tokio::test]
1366 async fn a_browser_and_a_json_client_do_not_share_a_key() {
1367 let browser = stamped(Some("text/html,application/xhtml+xml,*/*;q=0.8")).await;
1368 let json = stamped(Some("application/json")).await;
1369 assert_ne!(
1370 browser, json,
1371 "browser and JSON callers must key differently or the page \
1372 cache will serve one the other's representation"
1373 );
1374 }
1375}