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
708async fn handle_page_request(
709 tenant: Tenant,
710 State(state): State<PublicState>,
711 rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
712 rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
713 headers: axum::http::HeaderMap,
714 uri: Uri,
715) -> Response {
716 let viewer = member.as_ref().or(session_user.as_ref());
722 let raw_path = uri.path();
723 let _perf_t = crate::perf::start();
728 if let Some(resp) = crate::redirect::serve_override(
729 &tenant,
730 state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl)),
731 raw_path,
732 uri.query(),
733 )
734 .await
735 {
736 crate::perf::mark("redirect_rules", _perf_t);
737 return resp;
738 }
739 crate::perf::mark("redirect_rules", _perf_t);
740 let accept_language = headers
745 .get(axum::http::header::ACCEPT_LANGUAGE)
746 .and_then(|v| v.to_str().ok());
747 let accept = crate::page_view::parse_accept(
751 headers
752 .get(axum::http::header::ACCEPT)
753 .and_then(|v| v.to_str().ok()),
754 );
755 let cookie_code = crate::locale_mode::locale_cookie_value(
758 headers
759 .get(axum::http::header::COOKIE)
760 .and_then(|v| v.to_str().ok()),
761 );
762 let _perf_t = crate::perf::start();
763 let request_locale = resolve_request_locale(
764 tenant.pool(),
765 state.locale_mode,
766 raw_path,
767 uri.query(),
768 cookie_code.as_deref(),
769 accept_language,
770 )
771 .await;
772 crate::perf::mark("locale", _perf_t);
773 let locale_code = request_locale.code.clone();
774 let locale_explicit = request_locale.explicit;
775 let lookup_path = request_locale.stripped_path;
776
777 let _perf_t = crate::perf::start();
781 let site_prefix = crate::site::prefix_for_host(tenant.pool(), host_header(&headers))
782 .await
783 .unwrap_or_default();
784 crate::perf::mark("site", _perf_t);
785 let lookup_path = crate::site::to_lookup_path(&site_prefix, &lookup_path);
788
789 let _perf_t = crate::perf::start();
790 let _resolved = resolve_path(&tenant, &lookup_path).await;
791 crate::perf::mark("resolve_path", _perf_t);
792 match _resolved {
793 Ok(Some(page)) => {
794 let _perf_t = crate::perf::start();
799 let _blocked =
800 crate::view_restriction_guard::enforce(&tenant, &page, viewer, &headers, raw_path)
801 .await;
802 crate::perf::mark("view_restriction", _perf_t);
803 if let Some(blocked) = _blocked {
804 return styled_denial(&tenant, &state, blocked, locale_code.as_deref()).await;
805 }
806 if let Some(resp) = crate::hooks::fire_before_serve_page(&page, &headers) {
809 return resp;
810 }
811 let _perf_t = crate::perf::start();
817 let tera = state.tera_for(&tenant.org.slug).await;
821 let _switcher =
825 install_locale_switcher(&tenant, &state, &page, locale_code.as_deref()).await;
826 let _origin = crate::meta_tags::stash_site_origin(crate::sitemap::base_url(&headers));
829 let resp = render_negotiated(
830 &tenant,
831 &tera,
832 &page,
833 &state.url_prefix,
834 &site_prefix,
835 locale_code.as_deref(),
836 viewer,
837 accept,
838 state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl)),
839 )
840 .await;
841 crate::perf::mark("render", _perf_t);
842 let resp = if resp.status().is_server_error() {
846 crate::error_pages::respond(&tenant, &state, resp.status(), locale_code.as_deref())
847 .await
848 } else {
849 resp
850 };
851 persist_locale(resp, locale_explicit, locale_code.as_deref())
852 }
853 Ok(None) => {
854 match resolve_routable(&tenant, &lookup_path).await {
860 Ok(Some((page, route_match))) => {
861 if let Some(blocked) = crate::view_restriction_guard::enforce(
862 &tenant, &page, viewer, &headers, raw_path,
863 )
864 .await
865 {
866 return styled_denial(&tenant, &state, blocked, locale_code.as_deref()).await;
867 }
868 if let Some(resp) = crate::hooks::fire_before_serve_page(&page, &headers) {
869 return resp;
870 }
871 let tera = state.tera_for(&tenant.org.slug).await;
872 let _switcher =
873 install_locale_switcher(&tenant, &state, &page, locale_code.as_deref())
874 .await;
875 let _origin =
876 crate::meta_tags::stash_site_origin(crate::sitemap::base_url(&headers));
877 let resp = render_with_route(
878 &tenant,
879 &tera,
880 &page,
881 &state.url_prefix,
882 &site_prefix,
883 locale_code.as_deref(),
884 viewer,
885 &route_match,
886 accept,
887 state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl)),
888 )
889 .await;
890 let resp = if resp.status().is_server_error() {
891 crate::error_pages::respond(
892 &tenant,
893 &state,
894 resp.status(),
895 locale_code.as_deref(),
896 )
897 .await
898 } else {
899 resp
900 };
901 return persist_locale(resp, locale_explicit, locale_code.as_deref());
902 }
903 Ok(None) => {}
904 Err(e) => {
905 tracing::error!(path = %raw_path, error = %e, "resolve_routable failed");
906 }
907 }
908 fallthrough_to_redirect(
909 &tenant,
910 &state,
911 raw_path,
912 uri.query(),
913 locale_code.as_deref(),
914 )
915 .await
916 }
917 Err(e) => {
918 tracing::error!(path = %raw_path, error = %e, "resolve_path failed");
919 crate::error_pages::respond(
920 &tenant,
921 &state,
922 StatusCode::INTERNAL_SERVER_ERROR,
923 locale_code.as_deref(),
924 )
925 .await
926 }
927 }
928}
929
930fn persist_locale(mut resp: Response, explicit: bool, code: Option<&str>) -> Response {
938 use axum::http::header::{HeaderValue, SET_COOKIE, VARY};
939 resp.headers_mut()
940 .append(VARY, HeaderValue::from_static("Cookie"));
941 if explicit {
942 if let Some(code) = code {
943 let cookie = format!(
944 "{}={code}; Path=/; SameSite=Lax; HttpOnly; Max-Age=31536000",
945 crate::locale_mode::LOCALE_COOKIE
946 );
947 if let Ok(hv) = HeaderValue::from_str(&cookie) {
948 resp.headers_mut().append(SET_COOKIE, hv);
949 }
950 }
951 }
952 resp
953}
954
955async fn styled_denial(
959 tenant: &Tenant,
960 state: &PublicState,
961 blocked: Response,
962 locale_code: Option<&str>,
963) -> Response {
964 if blocked.status() == StatusCode::FORBIDDEN {
965 crate::error_pages::respond(tenant, state, StatusCode::FORBIDDEN, locale_code).await
966 } else {
967 blocked
968 }
969}
970
971pub(crate) async fn install_locale_switcher(
982 tenant: &Tenant,
983 state: &PublicState,
984 page: &crate::page::Page,
985 current_code: Option<&str>,
986) -> crate::language_switcher::PendingGuard {
987 use rustango::core::Column as _;
988 use rustango::sql::FetcherPool as _;
989 let locales: Vec<crate::locale::Locale> = crate::locale::Locale::objects()
990 .where_(crate::locale::Locale::active.eq(true))
991 .order_by(&[("sort_order", false)])
992 .fetch(tenant.pool())
993 .await
994 .unwrap_or_default();
995 let entries = crate::language_switcher::build(
996 &locales,
997 &state.url_prefix,
998 &page.url_path,
999 state.locale_mode,
1000 current_code,
1001 );
1002 crate::language_switcher::stash_pending(entries)
1003}
1004
1005async fn fallthrough_to_redirect(
1016 tenant: &Tenant,
1017 state: &PublicState,
1018 raw_path: &str,
1019 query: Option<&str>,
1020 locale_code: Option<&str>,
1021) -> Response {
1022 match crate::redirect::find_for_path(tenant.pool(), raw_path).await {
1023 Ok(Some(row)) => {
1024 let to = crate::redirect::resolve_destination(tenant.pool(), &row).await;
1027 let rule = rustango::redirects::RedirectRule {
1028 to,
1029 permanent: row.is_permanent,
1030 };
1031 let resp = rustango::redirects::build_redirect_response(&rule, query);
1032 crate::redirect::record_hit(
1035 tenant.pool(),
1036 &tenant.org.slug,
1037 row.id.get().copied().unwrap_or_default(),
1038 );
1039 resp
1040 }
1041 Ok(None) => {
1045 let cache = state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl));
1046 if let Some(resp) =
1047 crate::redirect::serve_wildcard(tenant, cache, raw_path, query).await
1048 {
1049 return resp;
1050 }
1051 crate::error_pages::respond(tenant, state, StatusCode::NOT_FOUND, locale_code).await
1052 }
1053 Err(e) => {
1054 tracing::warn!(path = %raw_path, error = %e, "redirect lookup failed");
1055 crate::error_pages::respond(tenant, state, StatusCode::NOT_FOUND, locale_code).await
1056 }
1057 }
1058}
1059
1060#[derive(Debug, serde::Deserialize)]
1065struct PasswordPromptQuery {
1066 page: i64,
1067 #[serde(default)]
1068 next: Option<String>,
1069 #[serde(default)]
1070 error: Option<String>,
1071}
1072
1073#[derive(Debug, serde::Deserialize)]
1074struct PasswordSubmitForm {
1075 page: i64,
1076 password: String,
1077 #[serde(default)]
1078 next: Option<String>,
1079}
1080
1081async fn handle_view_password_form(
1082 tenant: Tenant,
1083 State(state): State<PublicState>,
1084 headers: axum::http::HeaderMap,
1085 axum::extract::Query(q): axum::extract::Query<PasswordPromptQuery>,
1086) -> Response {
1087 use rustango::core::Column as _;
1088 use rustango::sql::FetcherPool as _;
1089 let _ = &tenant;
1090 let page_rows: Vec<crate::page::Page> = crate::page::Page::objects()
1091 .where_(crate::page::Page::id.eq(q.page))
1092 .fetch(tenant.pool())
1093 .await
1094 .unwrap_or_default();
1095 let title = page_rows
1096 .first()
1097 .map(|p| p.title.clone())
1098 .unwrap_or_else(|| "Protected page".to_owned());
1099 let next = q.next.clone().unwrap_or_else(|| "/".to_owned());
1100 let error_msg = q.error.as_deref().unwrap_or("");
1101 let mut ctx = tera::Context::new();
1102 ctx.insert("page_id", &q.page);
1103 ctx.insert("page_title", &title);
1104 ctx.insert("next_path", &next);
1105 ctx.insert("error_message", &error_msg);
1106 let (csrf_token, csrf_cookie) =
1109 rustango::forms::csrf::ensure_token(&headers, rustango::forms::csrf::CSRF_COOKIE);
1110 ctx.insert("csrf_token", &csrf_token);
1111 match state.tera.render("rcms/view_password.html", &ctx) {
1112 Ok(body) => {
1113 let mut resp = axum::response::Html(body).into_response();
1114 if let Some(v) = csrf_cookie.and_then(|c| axum::http::HeaderValue::from_str(&c).ok()) {
1115 resp.headers_mut().append(axum::http::header::SET_COOKIE, v);
1116 }
1117 resp
1118 }
1119 Err(e) => {
1120 tracing::error!(error = %e, "view-password template render failed");
1121 (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
1122 }
1123 }
1124}
1125
1126async fn handle_view_password_submit(
1127 tenant: Tenant,
1128 axum::extract::Form(form): axum::extract::Form<PasswordSubmitForm>,
1129) -> Response {
1130 let Some(restriction) = crate::view_restriction::direct_for_page(tenant.pool(), form.page)
1131 .await
1132 .unwrap_or(None)
1133 .filter(|r| r.kind == crate::view_restriction::RestrictionKind::Password.as_str())
1134 else {
1135 return (
1136 StatusCode::BAD_REQUEST,
1137 "no password restriction on this page",
1138 )
1139 .into_response();
1140 };
1141 let _ = &tenant;
1142 let _ = &restriction.password_hash;
1143 let ok =
1145 crate::passwords::verify(&form.password, &restriction.password_hash).await.unwrap_or(false);
1146 let next = form
1148 .next
1149 .as_deref()
1150 .and_then(rustango::auth_decorators::safe_next)
1151 .unwrap_or_else(|| "/".to_owned());
1152 if !ok {
1153 let next_enc = crate::view_restriction_guard::url_encode_path(&next);
1154 return Redirect::to(&format!(
1155 "/__cms-view-password?page={}&next={next_enc}&error=Wrong+password",
1156 form.page
1157 ))
1158 .into_response();
1159 }
1160 let cookie =
1163 crate::view_restriction_guard::grant_cookie(&tenant.org.slug, &restriction, form.page);
1164 let mut response = Redirect::to(&next).into_response();
1165 if let Ok(hv) = axum::http::HeaderValue::from_str(&cookie) {
1166 response
1167 .headers_mut()
1168 .append(axum::http::header::SET_COOKIE, hv);
1169 }
1170 response
1171}
1172
1173#[cfg(test)]
1174mod static_serve_tests {
1175 use super::*;
1176 use std::fs;
1177 use std::path::PathBuf;
1178
1179 fn tempdir(name: &str) -> PathBuf {
1183 let mut p = std::env::temp_dir();
1184 p.push(format!("rustango_cms_static_{name}_{}", std::process::id()));
1185 let _ = fs::remove_dir_all(&p);
1186 fs::create_dir_all(&p).expect("create tempdir");
1187 p
1188 }
1189
1190 #[test]
1191 fn serves_existing_file_with_guessed_mime() {
1192 let dir = tempdir("hit");
1193 fs::write(dir.join("styles.css"), b"body{color:red}").unwrap();
1194 let resp = serve_static_path(&dir, "styles.css");
1195 assert_eq!(resp.status(), axum::http::StatusCode::OK);
1196 let ct = resp
1197 .headers()
1198 .get(axum::http::header::CONTENT_TYPE)
1199 .unwrap()
1200 .to_str()
1201 .unwrap();
1202 assert!(ct.starts_with("text/css"), "got `{ct}`");
1203 let cc = resp
1204 .headers()
1205 .get(axum::http::header::CACHE_CONTROL)
1206 .unwrap()
1207 .to_str()
1208 .unwrap();
1209 assert!(cc.contains("max-age=3600"));
1210 }
1211
1212 #[test]
1213 fn rejects_dotdot_traversal_in_segment() {
1214 let dir = tempdir("trav");
1215 fs::write(dir.join("ok.txt"), b"in-root").unwrap();
1216 let resp = serve_static_path(&dir, "../etc/passwd");
1218 assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1219 }
1220
1221 #[test]
1222 fn rejects_absolute_segment() {
1223 let dir = tempdir("abs");
1224 let resp = serve_static_path(&dir, "/etc/passwd");
1226 assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1227 }
1228
1229 #[test]
1230 fn rejects_null_byte_in_path() {
1231 let dir = tempdir("null");
1232 let resp = serve_static_path(&dir, "ok\0.txt");
1233 assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1234 }
1235
1236 #[test]
1237 fn missing_file_is_404_not_500() {
1238 let dir = tempdir("miss");
1239 let resp = serve_static_path(&dir, "does-not-exist.css");
1240 assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1241 }
1242
1243 #[test]
1244 fn serves_static_bytes_with_supplied_content_type() {
1245 let resp = serve_static_bytes(b"<svg/>", "image/svg+xml");
1246 assert_eq!(resp.status(), axum::http::StatusCode::OK);
1247 assert_eq!(
1248 resp.headers()
1249 .get(axum::http::header::CONTENT_TYPE)
1250 .and_then(|v| v.to_str().ok()),
1251 Some("image/svg+xml"),
1252 );
1253 }
1254
1255 #[test]
1256 fn nested_subdir_is_served() {
1257 let dir = tempdir("nested");
1258 fs::create_dir_all(dir.join("css/sub")).unwrap();
1259 fs::write(dir.join("css/sub/x.css"), b"x{}").unwrap();
1260 let resp = serve_static_path(&dir, "css/sub/x.css");
1261 assert_eq!(resp.status(), axum::http::StatusCode::OK);
1262 }
1263
1264 #[test]
1265 fn empty_path_is_404() {
1266 let dir = tempdir("empty");
1267 let resp = serve_static_path(&dir, "");
1268 assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1269 }
1270}
1271
1272#[cfg(test)]
1273mod accept_cache_key_tests {
1274 use super::*;
1275 use axum::http::{HeaderValue, Request};
1276
1277 fn req_with_accept(accept: Option<&str>) -> axum::extract::Request {
1278 let mut b = Request::builder().uri("/some-page");
1279 if let Some(a) = accept {
1280 b = b.header(
1281 axum::http::header::ACCEPT,
1282 HeaderValue::from_str(a).unwrap(),
1283 );
1284 }
1285 b.body(axum::body::Body::empty()).unwrap()
1286 }
1287
1288 async fn stamped(accept: Option<&str>) -> Option<String> {
1289 let req = inject_accept_kind_header(req_with_accept(accept)).await;
1290 req.headers()
1291 .get("x-rcms-accept")
1292 .and_then(|v| v.to_str().ok())
1293 .map(str::to_owned)
1294 }
1295
1296 #[tokio::test]
1300 async fn only_an_explicit_json_preference_changes_the_cache_key() {
1301 assert_eq!(
1302 stamped(Some("application/json")).await.as_deref(),
1303 Some("json")
1304 );
1305 assert_eq!(
1306 stamped(Some("application/json, text/plain, */*"))
1307 .await
1308 .as_deref(),
1309 Some("json")
1310 );
1311
1312 let chrome = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,\
1314 image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7";
1315 assert_eq!(stamped(Some(chrome)).await, None);
1316 assert_eq!(stamped(Some("*/*")).await, None);
1317 assert_eq!(stamped(None).await, None);
1318 assert_eq!(
1320 stamped(Some("application/json;q=0.1, text/html")).await,
1321 None
1322 );
1323 assert_eq!(stamped(Some("application/json;q=0")).await, None);
1325 }
1326
1327 #[tokio::test]
1331 async fn a_browser_and_a_json_client_do_not_share_a_key() {
1332 let browser = stamped(Some("text/html,application/xhtml+xml,*/*;q=0.8")).await;
1333 let json = stamped(Some("application/json")).await;
1334 assert_ne!(
1335 browser, json,
1336 "browser and JSON callers must key differently or the page \
1337 cache will serve one the other's representation"
1338 );
1339 }
1340}