1use std::sync::Arc;
34
35use axum::http::StatusCode;
36use axum::response::{IntoResponse, Response};
37use axum::routing::{get, post};
38use axum::Router;
39use serde::Deserialize;
40use tera::Tera;
41
42use crate::page::PageStatus;
43use crate::tree_ops::TreeError;
44
45pub mod admin_page;
46
47pub use handlers::add_chrome;
56pub use handlers::issue_password_reset_link;
57
58pub mod chooser;
59mod handlers;
60mod i18n;
61pub(crate) mod members;
62pub use members::{authenticate_member, MemberLoginError};
63pub use i18n::extend_ui_catalog;
67pub mod model_admin;
68pub mod pagination;
69pub mod report;
70pub mod resources;
71mod route_perms;
72pub(crate) mod notifications;
73pub(crate) mod sites;
74pub(crate) mod template_editor;
75pub use template_editor::CODENAME as TEMPLATE_EDIT_CODENAME;
78pub use notifications::CODENAME as NOTIFICATION_MANAGE_CODENAME;
81pub use sites::CODENAME as SITE_MANAGE_CODENAME;
84pub(crate) use template_editor::offerable as template_offerable;
87pub use handlers::ListQuery;
88pub(crate) use handlers::{
90 allowed_children_for, allowed_root_types, apply_page_edit, dedup_slug_under_parent,
91 media_picker_payload, slugify, store_media, upsert_page_translations, MediaPickerQuery,
92 PageEditActor, PageEditOutcome, PageEditRefusal,
93};
94
95#[derive(Clone)]
101pub(crate) struct AdminState {
102 pub(crate) tera: Arc<Tera>,
103 pub(crate) signing_secret: Arc<Vec<u8>>,
109 pub(crate) cache_invalidator: Arc<dyn crate::cache_invalidate::PageCacheInvalidator>,
116 pub(crate) mailer: Option<Arc<dyn rustango::email::Mailer>>,
121 pub(crate) mailer_from: Arc<String>,
125}
126
127pub fn router(tera: Arc<Tera>) -> Router {
138 let secret = crate::signing::derived_key(PASSWORD_RESET_KEY_PURPOSE);
139 crate::perf::instrument(router_with_state(AdminState {
140 tera,
141 signing_secret: Arc::new(secret),
142 cache_invalidator: crate::cache_invalidate::noop(),
143 mailer: None,
144 mailer_from: Arc::new(String::new()),
145 }))
146}
147
148pub fn router_with_invalidator(
153 tera: Arc<Tera>,
154 invalidator: Arc<dyn crate::cache_invalidate::PageCacheInvalidator>,
155) -> Router {
156 let secret = crate::signing::derived_key(PASSWORD_RESET_KEY_PURPOSE);
157 crate::task_queue::set_default_invalidator(Arc::clone(&invalidator));
159 router_with_state(AdminState {
160 tera,
161 signing_secret: Arc::new(secret),
162 cache_invalidator: invalidator,
163 mailer: None,
164 mailer_from: Arc::new(String::new()),
165 })
166}
167
168pub fn router_with_mailer(
174 tera: Arc<Tera>,
175 invalidator: Arc<dyn crate::cache_invalidate::PageCacheInvalidator>,
176 mailer: Arc<dyn rustango::email::Mailer>,
177 from_addr: impl Into<String>,
178) -> Router {
179 let secret = crate::signing::derived_key(PASSWORD_RESET_KEY_PURPOSE);
180 crate::task_queue::set_default_invalidator(Arc::clone(&invalidator));
182 router_with_state(AdminState {
183 tera,
184 signing_secret: Arc::new(secret),
185 cache_invalidator: invalidator,
186 mailer: Some(mailer),
187 mailer_from: Arc::new(from_addr.into()),
188 })
189}
190
191pub fn public_router(tera: Arc<Tera>) -> Router {
207 public_router_inner(tera, None, String::new())
208}
209
210pub fn public_router_with_mailer(
215 tera: Arc<Tera>,
216 mailer: Arc<dyn rustango::email::Mailer>,
217 from_addr: impl Into<String>,
218) -> Router {
219 public_router_inner(tera, Some(mailer), from_addr.into())
220}
221
222fn public_router_inner(
223 tera: Arc<Tera>,
224 mailer: Option<Arc<dyn rustango::email::Mailer>>,
225 mailer_from: String,
226) -> Router {
227 let secret = crate::signing::derived_key(PASSWORD_RESET_KEY_PURPOSE);
228 let state = AdminState {
229 tera,
230 signing_secret: Arc::new(secret),
231 cache_invalidator: crate::cache_invalidate::noop(),
232 mailer,
233 mailer_from: Arc::new(mailer_from),
234 };
235 Router::new()
236 .route(
237 "/cms-admin/password-reset",
238 get(handlers::password_reset_request_form)
239 .post(handlers::password_reset_request_submit),
240 )
241 .route(
242 "/cms-admin/password-reset/confirm",
243 get(handlers::password_reset_confirm_form)
244 .post(handlers::password_reset_confirm_submit),
245 )
246 .route("/login", get(handlers::cms_login_form))
251 .route(
258 "/members/login",
259 get(members::member_login_form).post(members::member_login_submit),
260 )
261 .route(
262 "/members/signup",
263 get(members::member_signup_form).post(members::member_signup_submit),
264 )
265 .route("/members/logout", post(members::member_logout))
266 .route(
271 "/__cms-branding/logo",
272 get(handlers::settings_branding_serve_logo),
273 )
274 .route(
275 "/__cms-branding/favicon",
276 get(handlers::settings_branding_serve_favicon),
277 )
278 .route("/cms-admin/no-access", get(handlers::no_access_page))
282 .route("/cms-admin/static/cms.css", get(serve_cms_css))
286 .route("/cms-admin/static/fonts.css", get(serve_admin_fonts_css))
297 .route(
298 "/cms-admin/static/vendor/fonts/{file}",
299 get(serve_admin_font_file),
300 )
301 .route("/cms-admin/static/brand/{file}", get(serve_admin_brand_file))
305 .route("/cms-admin/static/cms-ux.js", get(serve_cms_ux_js))
306 .route(
307 "/cms-admin/static/stream_editor.js",
308 get(serve_stream_editor_js),
309 )
310 .route("/cms-admin/static/block_tree.js", get(serve_block_tree_js))
313 .route("/cms-admin/static/cms-preview.js", get(serve_cms_preview_js))
314 .route(
315 "/cms-admin/static/menu-builder.js",
316 get(serve_menu_builder_js),
317 )
318 .route(
320 "/cms-admin/static/form_builder.js",
321 get(serve_form_builder_js),
322 )
323 .route(
324 "/cms-admin/static/page_type_builder.js",
325 get(serve_page_type_builder_js),
326 )
327 .route(
329 "/cms-admin/static/page_builder_rules.js",
330 get(serve_page_builder_rules_js),
331 )
332 .route(
337 "/cms-admin/static/vendor/axe-core.min.js",
338 get(serve_axe_core_js),
339 )
340 .route(
344 "/cms-admin/static/cms-axe-preview.js",
345 get(serve_cms_axe_preview_js),
346 )
347 .route(
350 "/cms-admin/static/cms-preview-guard.js",
351 get(serve_cms_preview_guard_js),
352 )
353 .route(
356 "/cms-admin/static/template-editor.js",
357 get(serve_template_editor_js),
358 )
359 .route(
360 "/cms-admin/static/vendor/codemirror.bundle.js",
361 get(serve_codemirror_bundle_js),
362 )
363 .route(
364 "/cms-admin/static/vendor/tiptap.bundle.js",
365 get(serve_tiptap_bundle_js),
366 )
367 .route(
368 "/cms-admin/static/richtext-editor.js",
369 get(serve_richtext_editor_js),
370 )
371 .route(
373 "/cms-admin/static/vendor/THIRD-PARTY-NOTICES.txt",
374 get(serve_third_party_notices),
375 )
376 .route_layer(axum::middleware::from_fn(i18n::tenant_overrides_layer))
378 .with_state(state)
379}
380
381async fn serve_third_party_notices() -> impl axum::response::IntoResponse {
385 (
386 [(
387 axum::http::header::CONTENT_TYPE,
388 axum::http::HeaderValue::from_static("text/plain; charset=utf-8"),
389 )],
390 include_str!("static/vendor/THIRD-PARTY-NOTICES.txt"),
391 )
392}
393
394const PASSWORD_RESET_KEY_PURPOSE: &str = "rcms:password-reset";
397
398pub fn with_login_required(router: Router, login_url: impl Into<String> + 'static) -> Router {
427 use axum::middleware::{from_fn, Next};
428 let login_url: Arc<str> = Arc::from(login_url.into());
429 router.layer(from_fn(
430 move |req: axum::http::Request<axum::body::Body>, next: Next| {
431 let login_url = login_url.clone();
432 async move {
433 use axum::extract::FromRequestParts as _;
434 let (mut parts, body) = req.into_parts();
435 let user = rustango::extractors::SessionUser::from_request_parts(&mut parts, &())
436 .await
437 .unwrap_or(rustango::extractors::SessionUser(None));
438 if let Some(user) = user.0 {
439 let allowed = user.is_superuser
446 || parts.uri.path().starts_with("/cms-admin/static/")
447 || matches!(
448 check_codename(&mut parts, "cms_admin.access").await,
449 AccessResult::Allowed
450 );
451 if !allowed {
452 use axum::response::IntoResponse as _;
453 return axum::response::Redirect::to("/cms-admin/no-access").into_response();
454 }
455 let req = axum::http::Request::from_parts(parts, body);
456 return next.run(req).await;
457 }
458 let original = parts
462 .uri
463 .path_and_query()
464 .map(|p| p.as_str().to_owned())
465 .unwrap_or_else(|| "/".to_owned());
466 rustango::auth_decorators::redirect_to_login(&login_url, "next", &original)
467 }
468 },
469 ))
470}
471
472pub fn with_cms_admin_access(router: Router, no_access_url: impl Into<String>) -> Router {
487 with_codename_gate(router, "cms_admin.access", no_access_url)
488}
489
490pub fn with_codename_gate(
497 router: Router,
498 codename: &'static str,
499 no_access_url: impl Into<String>,
500) -> Router {
501 use axum::middleware::{from_fn, Next};
502 use axum::response::{IntoResponse, Redirect};
503 let no_access_url: Arc<str> = Arc::from(no_access_url.into());
504 router.layer(from_fn(
505 move |req: axum::http::Request<axum::body::Body>, next: Next| {
506 let no_access_url = no_access_url.clone();
507 async move {
508 let path = req.uri().path();
509 if path == &*no_access_url || path.starts_with("/cms-admin/static/") {
510 return next.run(req).await;
511 }
512 let (mut parts, body) = req.into_parts();
513 let outcome = check_codename(&mut parts, codename).await;
514 let req = axum::http::Request::from_parts(parts, body);
515 match outcome {
516 AccessResult::Allowed | AccessResult::DeniedNoUser => next.run(req).await,
517 AccessResult::Denied => Redirect::to(&no_access_url).into_response(),
518 }
519 }
520 },
521 ))
522}
523
524enum AccessResult {
525 Allowed,
526 Denied,
527 DeniedNoUser,
530}
531
532pub(crate) async fn codename_gate(
545 tenant: &rustango::extractors::Tenant,
546 user: Option<&rustango::tenancy::auth::User>,
547 codename: &str,
548) -> Option<axum::response::Response> {
549 use axum::response::{IntoResponse, Redirect};
550 let Some(user) = user else {
551 return Some(Redirect::to("/login").into_response());
552 };
553 if user.is_superuser {
554 return None;
555 }
556 let uid = user.id.get().copied().unwrap_or_default();
557 let codes = crate::permissions::user_codenames(tenant.pool(), uid)
558 .await
559 .unwrap_or_default();
560 if codes.contains(codename) {
561 None
562 } else {
563 Some(Redirect::to("/cms-admin/no-access").into_response())
564 }
565}
566
567async fn check_codename(parts: &mut axum::http::request::Parts, codename: &str) -> AccessResult {
568 let (user, pool) = match request_user_and_pool(parts).await {
569 Ok(Some(found)) => found,
570 Ok(None) => return AccessResult::DeniedNoUser,
571 Err(()) => return AccessResult::Denied,
572 };
573 if user.is_superuser {
574 return AccessResult::Allowed;
575 }
576 let uid = user.id.get().copied().unwrap_or_default();
577 let codenames = crate::permissions::user_codenames(&pool, uid)
578 .await
579 .unwrap_or_default();
580 if codenames.contains(codename) {
581 AccessResult::Allowed
582 } else {
583 AccessResult::Denied
584 }
585}
586
587pub(crate) async fn request_user_and_pool(
592 parts: &mut axum::http::request::Parts,
593) -> Result<Option<(rustango::tenancy::auth::User, rustango::sql::Pool)>, ()> {
594 use axum::extract::FromRequestParts as _;
595 use rustango::tenancy::OrgResolver as _;
596 use std::sync::Arc;
597
598 let Some(ctx) = parts
599 .extensions
600 .get::<Arc<rustango::extractors::TenantContext>>()
601 .cloned()
602 else {
603 return Ok(None);
604 };
605 let Ok(rustango::extractors::SessionUser(Some(user))) =
608 rustango::extractors::SessionUser::from_request_parts(parts, &()).await
609 else {
610 return Ok(None);
611 };
612 let Ok(Some(org)) = ctx.resolver.resolve(parts, &ctx.pools.registry_pool()).await else {
613 return Ok(None);
614 };
615 let pool = ctx.pools.scoped_pool_dyn(&org).await.map_err(|_| ())?;
616 Ok(Some((user, pool)))
617}
618
619fn router_with_state(state: AdminState) -> Router {
620 Router::new()
621 .route("/cms-admin", get(redirect_root))
623 .route("/cms-admin/", get(redirect_root))
624 .route("/cms-admin/pages", get(handlers::page_list))
625 .route(
626 "/cms-admin/pages/new",
627 get(handlers::page_new_form).post(handlers::page_new_submit),
628 )
629 .route(
630 "/cms-admin/pages/{id}/edit",
631 get(handlers::page_edit_form).post(handlers::page_edit_submit),
632 )
633 .route(
634 "/cms-admin/pages/{id}/translate",
635 post(handlers::page_translate_submit),
636 )
637 .route(
638 "/cms-admin/pages/{id}/delete",
639 post(handlers::page_delete_submit),
640 )
641 .route(
642 "/cms-admin/pages/{id}/preview",
643 get(handlers::page_preview).post(handlers::page_preview_draft),
644 )
645 .route(
647 "/cms-admin/pages/{id}/preview-token",
648 get(handlers::page_preview_token),
649 )
650 .route(
652 "/cms-admin/pages/{id}/revert/{rev_id}",
653 post(handlers::page_revert_submit),
654 )
655 .route(
657 "/cms-admin/pages/{id}/history/diff",
658 get(handlers::history_diff),
659 )
660 .route("/cms-admin/pages/{id}/log.csv", get(handlers::page_log_csv))
662 .route(
665 "/cms-admin/pages/{id}/permissions",
666 post(handlers::page_permissions_submit),
667 )
668 .route(
670 "/cms-admin/pages/{id}/move",
671 post(handlers::page_move_submit),
672 )
673 .route(
675 "/cms-admin/pages/{id}/clone",
676 post(handlers::page_clone_submit),
677 )
678 .route(
680 "/cms-admin/pages/{id}/alias",
681 post(handlers::page_alias_submit),
682 )
683 .route(
685 "/cms-admin/pages/{id}/privacy",
686 post(handlers::page_privacy_submit),
687 )
688 .route("/cms-admin/pages/bulk", post(handlers::page_bulk_submit))
692 .route(
694 "/cms-admin/pages/{id}/unlock",
695 post(handlers::page_unlock_submit),
696 )
697 .route(
698 "/cms-admin/pages/{id}/lock-release",
699 post(handlers::page_lock_release),
700 )
701 .route(
702 "/cms-admin/pages/{id}/lock-heartbeat",
703 post(handlers::page_lock_heartbeat),
704 )
705 .route(
707 "/cms-admin/pages/{id}/autosave",
708 post(handlers::page_autosave_submit),
709 )
710 .route(
712 "/cms-admin/pages/{id}/sessions",
713 get(handlers::page_sessions_json),
714 )
715 .route(
717 "/cms-admin/pages/{id}/subscribe",
718 post(handlers::page_subscribe_submit),
719 )
720 .route(
721 "/cms-admin/pages/{id}/unsubscribe",
722 post(handlers::page_unsubscribe_submit),
723 )
724 .route(
726 "/cms-admin/pages/{id}/comments/new",
727 post(handlers::comment_new_submit),
728 )
729 .route(
730 "/cms-admin/pages/{id}/comments/{comment_id}/reply",
731 post(handlers::comment_reply_submit),
732 )
733 .route(
734 "/cms-admin/pages/{id}/comments/{comment_id}/resolve",
735 post(handlers::comment_resolve_submit),
736 )
737 .route(
738 "/cms-admin/pages/{id}/comments/{comment_id}/reopen",
739 post(handlers::comment_reopen_submit),
740 )
741 .route(
743 "/cms-admin/pages/{id}/workflow/submit",
744 post(handlers::page_workflow_submit),
745 )
746 .route(
747 "/cms-admin/pages/{id}/workflow/approve",
748 post(handlers::page_workflow_approve),
749 )
750 .route(
751 "/cms-admin/pages/{id}/workflow/reject",
752 post(handlers::page_workflow_reject),
753 )
754 .route(
755 "/cms-admin/pages/{id}/workflow/cancel",
756 post(handlers::page_workflow_cancel),
757 )
758 .route("/cms-admin/library", get(handlers::library_list))
760 .route("/cms-admin/forms", get(handlers::forms_list))
764 .route("/cms-admin/set-language", post(handlers::admin_set_language))
766 .route(
769 "/cms-admin/forms/{id}/build",
770 get(handlers::form_build_form).post(handlers::form_build_submit),
771 )
772 .route(
775 "/cms-admin/forms/{id}/preview",
776 get(handlers::form_preview).post(handlers::form_preview_draft),
777 )
778 .route(
780 "/cms-admin/forms/{id}/publish",
781 post(handlers::form_publish_submit),
782 )
783 .route(
785 "/cms-admin/forms/{id}/submissions",
786 get(handlers::form_submissions_list),
787 )
788 .route(
789 "/cms-admin/forms/{id}/submissions/export.csv",
790 get(handlers::form_submissions_csv),
791 )
792 .route(
794 "/cms-admin/forms/{id}/submissions/file/{key}",
795 get(handlers::form_submission_file),
796 )
797 .route(
798 "/cms-admin/library/new",
799 get(handlers::snippet_new_form).post(handlers::snippet_create_submit),
800 )
801 .route(
802 "/cms-admin/library/{id}/edit",
803 get(handlers::snippet_edit_form).post(handlers::snippet_edit_submit),
804 )
805 .route(
807 "/cms-admin/library/{id}/translate",
808 post(handlers::snippet_translate_submit),
809 )
810 .route(
814 "/cms-admin/library/{type_name}/bulk",
815 post(handlers::library_bulk_submit),
816 )
817 .route(
818 "/cms-admin/library/{id}/delete",
819 post(handlers::snippet_delete_submit),
820 )
821 .route(
823 "/cms-admin/library/{id}/revert/{seq}",
824 post(handlers::snippet_revert_submit),
825 )
826 .route(
828 "/cms-admin/library/{type_name}/import",
829 get(handlers::snippet_import_form).post(handlers::snippet_import_submit),
830 )
831 .route("/cms-admin/media", get(handlers::media_list))
833 .route(
835 "/cms-admin/media/{id}/edit",
836 get(handlers::media_edit_form).post(handlers::media_edit_submit),
837 )
838 .route(
840 "/cms-admin/media/{id}/crop",
841 post(handlers::media_crop_submit),
842 )
843 .route(
845 "/cms-admin/media/{id}/replace",
846 post(handlers::media_replace_submit),
847 )
848 .route(
850 "/cms-admin/media/collections",
851 get(handlers::collections_list),
852 )
853 .route(
854 "/cms-admin/media/collections/new",
855 post(handlers::collections_create),
856 )
857 .route(
858 "/cms-admin/media/collections/{id}/edit",
859 post(handlers::collections_edit),
860 )
861 .route(
862 "/cms-admin/media/collections/{id}/delete",
863 post(handlers::collections_delete),
864 )
865 .route(
866 "/cms-admin/media/bulk-move-collection",
867 post(handlers::media_bulk_move_collection),
868 )
869 .route("/cms-admin/taxonomies", get(handlers::taxonomies_index))
872 .route("/cms-admin/taxonomies/{slug}", get(handlers::category_tree))
873 .route(
874 "/cms-admin/taxonomies/{slug}/categories/new",
875 get(handlers::category_new_form).post(handlers::category_create),
876 )
877 .route(
878 "/cms-admin/taxonomies/{slug}/categories/{id}/edit",
879 get(handlers::category_edit_form).post(handlers::category_update),
880 )
881 .route(
882 "/cms-admin/taxonomies/{slug}/categories/{id}/delete",
883 post(handlers::category_delete),
884 )
885 .route(
887 "/cms-admin/taxonomies/{slug}/categories/{id}/translate",
888 post(handlers::category_translate_submit),
889 )
890 .route(
892 "/cms-admin/media/collections/{id}/permissions",
893 get(handlers::collection_permissions_form)
894 .post(handlers::collection_permissions_submit),
895 )
896 .route(
898 "/cms-admin/media/collections/{id}/privacy",
899 post(handlers::collection_privacy_submit),
900 )
901 .route(
904 "/cms-admin/media/unused",
905 get(handlers::media_unused_report),
906 )
907 .route(
908 "/cms-admin/media/unused/delete",
909 post(handlers::media_unused_bulk_delete),
910 )
911 .route(
912 "/cms-admin/media/upload",
913 get(handlers::media_upload_form).post(handlers::media_upload_submit),
914 )
915 .route(
919 "/cms-admin/media/upload-staged",
920 post(handlers::media_upload_staged)
921 .route_layer(axum::extract::DefaultBodyLimit::max(50 * 1024 * 1024)),
922 )
923 .route(
924 "/cms-admin/media/upload-staged/{id}/cancel",
925 post(handlers::media_upload_staged_cancel),
926 )
927 .route(
929 "/cms-admin/media/upload-staged/commit",
930 post(handlers::media_upload_staged_commit),
931 )
932 .route(
933 "/cms-admin/media/{id}/delete",
934 post(handlers::media_delete_submit),
935 )
936 .route("/cms-admin/documents", get(handlers::documents_list))
937 .route("/cms-admin/model/{slug}", get(handlers::model_admin_list))
939 .route("/cms-admin/report/{slug}", get(handlers::report_view))
942 .route(
946 "/cms-admin/__chooser/{slug}",
947 get(handlers::chooser_search_json),
948 )
949 .route(
953 "/cms-admin/__media-picker",
954 get(handlers::media_picker_json),
955 )
956 .route("/cms-admin/sso-providers", get(handlers::sso_provider_list))
958 .route(
959 "/cms-admin/sso-providers/new",
960 get(handlers::sso_provider_new_form).post(handlers::sso_provider_new_submit),
961 )
962 .route(
963 "/cms-admin/sso-providers/{id}/edit",
964 get(handlers::sso_provider_edit_form).post(handlers::sso_provider_edit_submit),
965 )
966 .route(
967 "/cms-admin/sso-providers/{id}/delete",
968 post(handlers::sso_provider_delete_submit),
969 )
970 .route("/cms-admin/locales", get(handlers::locale_list))
972 .route(
973 "/cms-admin/locales/new",
974 get(handlers::locale_new_form).post(handlers::locale_new_submit),
975 )
976 .route(
977 "/cms-admin/locales/{id}/edit",
978 get(handlers::locale_edit_form).post(handlers::locale_edit_submit),
979 )
980 .route(
981 "/cms-admin/locales/{id}/delete",
982 post(handlers::locale_delete_submit),
983 )
984 .route("/cms-admin/search", get(handlers::admin_search))
988 .route(
991 "/cms-admin/site-settings",
992 get(handlers::site_settings_list),
993 )
994 .route(
995 "/cms-admin/site-settings/{scope}/edit",
996 get(handlers::site_setting_edit_form).post(handlers::site_setting_edit_submit),
997 )
998 .route(
999 "/cms-admin/site-settings/{scope}/delete",
1000 post(handlers::site_setting_delete_submit),
1001 )
1002 .route(
1004 "/cms-admin/site-settings/{scope}/translate",
1005 post(handlers::site_setting_translate_submit),
1006 )
1007 .route("/cms-admin/templates", get(template_editor::list))
1010 .route(
1011 "/cms-admin/templates/edit",
1012 get(template_editor::edit_form).post(template_editor::save),
1013 )
1014 .route("/cms-admin/templates/new", post(template_editor::create))
1015 .route(
1016 "/cms-admin/templates/validate",
1017 post(template_editor::validate),
1018 )
1019 .route("/cms-admin/templates/delete", post(template_editor::delete))
1020 .route(
1023 "/cms-admin/page-types/{id}/template",
1024 get(template_editor::assign_form).post(template_editor::assign_save),
1025 )
1026 .route("/cms-admin/analytics", get(handlers::analytics_dashboard))
1027 .route(
1028 "/cms-admin/reports/aging",
1029 get(handlers::aging_pages_report),
1030 )
1031 .route(
1032 "/cms-admin/reports/aging.csv",
1033 get(handlers::aging_pages_csv),
1034 )
1035 .route(
1036 "/cms-admin/reports/locked-pages",
1037 get(handlers::locked_pages_report),
1038 )
1039 .route(
1040 "/cms-admin/reports/locked-pages.csv",
1041 get(handlers::locked_pages_csv),
1042 )
1043 .route(
1044 "/cms-admin/reports/workflows",
1045 get(handlers::workflows_report),
1046 )
1047 .route(
1048 "/cms-admin/reports/workflows.csv",
1049 get(handlers::workflows_report_csv),
1050 )
1051 .route(
1053 "/cms-admin/reports/revisions",
1054 get(handlers::revisions_report),
1055 )
1056 .route(
1057 "/cms-admin/reports/revisions/prune",
1058 post(handlers::revisions_report_prune),
1059 )
1060 .route(
1062 "/cms-admin/reports/scheduled",
1063 get(handlers::scheduled_report),
1064 )
1065 .route(
1066 "/cms-admin/reports/scheduled.csv",
1067 get(handlers::scheduled_report_csv),
1068 )
1069 .route(
1071 "/cms-admin/reports/search",
1072 get(handlers::search_promotions_report),
1073 )
1074 .route(
1075 "/cms-admin/reports/search/{id}/edit",
1076 get(handlers::search_promotion_edit_form).post(handlers::search_promotion_edit_submit),
1077 )
1078 .route("/cms-admin/workflows", get(handlers::workflows_list))
1079 .route(
1080 "/cms-admin/workflows/new",
1081 get(handlers::workflow_new_form).post(handlers::workflow_new_submit),
1082 )
1083 .route(
1084 "/cms-admin/workflows/{id}/edit",
1085 get(handlers::workflow_edit_form).post(handlers::workflow_edit_submit),
1086 )
1087 .route(
1088 "/cms-admin/workflows/{id}/delete",
1089 post(handlers::workflow_delete_submit),
1090 )
1091 .route(
1092 "/cms-admin/workflows/{id}/tasks/add",
1093 post(handlers::workflow_task_add),
1094 )
1095 .route(
1096 "/cms-admin/workflows/{id}/tasks/{task_id}/delete",
1097 post(handlers::workflow_task_delete),
1098 )
1099 .route("/cms-admin/notifications", get(notifications::list))
1104 .route("/cms-admin/notifications/new", post(notifications::create))
1105 .route(
1106 "/cms-admin/notifications/{id}/toggle",
1107 post(notifications::toggle),
1108 )
1109 .route(
1110 "/cms-admin/notifications/{id}/delete",
1111 post(notifications::delete),
1112 )
1113 .route(
1114 "/cms-admin/notifications/deliveries/{id}/retry",
1115 post(notifications::retry_delivery),
1116 )
1117 .route("/cms-admin/sites", get(sites::list))
1122 .route("/cms-admin/sites/new", post(sites::add))
1123 .route("/cms-admin/sites/root", post(sites::set_root))
1124 .route("/cms-admin/sites/toggle", post(sites::toggle))
1125 .route("/cms-admin/sites/delete", post(sites::remove))
1126 .route("/cms-admin/redirects", get(handlers::redirect_list))
1127 .route(
1128 "/cms-admin/redirects/new",
1129 get(handlers::redirect_new_form).post(handlers::redirect_new_submit),
1130 )
1131 .route(
1132 "/cms-admin/redirects/{id}/edit",
1133 get(handlers::redirect_edit_form).post(handlers::redirect_edit_submit),
1134 )
1135 .route(
1136 "/cms-admin/redirects/{id}/delete",
1137 post(handlers::redirect_delete_submit),
1138 )
1139 .route(
1141 "/cms-admin/redirects/{id}/enable",
1142 post(handlers::redirect_enable_submit),
1143 )
1144 .route(
1146 "/cms-admin/redirects/import",
1147 get(handlers::redirect_import_form).post(handlers::redirect_import_submit),
1148 )
1149 .route(
1151 "/cms-admin/redirects/export.csv",
1152 get(handlers::redirect_export_csv),
1153 )
1154 .route("/cms-admin/users", get(handlers::users_list))
1156 .route("/cms-admin/users/bulk", post(handlers::users_bulk_submit))
1158 .route(
1159 "/cms-admin/users/new",
1160 get(handlers::users_new_form).post(handlers::users_create_submit),
1161 )
1162 .route(
1163 "/cms-admin/users/{id}/edit",
1164 get(handlers::users_edit_form).post(handlers::users_edit_submit),
1165 )
1166 .route(
1167 "/cms-admin/users/{id}/deactivate",
1168 post(handlers::users_deactivate_submit),
1169 )
1170 .route("/cms-admin/security-log", get(handlers::security_log_page))
1172 .route("/cms-admin/roles", get(handlers::roles_list))
1173 .route(
1175 "/cms-admin/permissions",
1176 get(handlers::permissions_overview),
1177 )
1178 .route(
1179 "/cms-admin/roles/new",
1180 get(handlers::roles_new_form).post(handlers::roles_create_submit),
1181 )
1182 .route(
1183 "/cms-admin/roles/{id}/edit",
1184 get(handlers::roles_edit_form).post(handlers::roles_edit_submit),
1185 )
1186 .route(
1187 "/cms-admin/roles/{id}/delete",
1188 post(handlers::roles_delete_submit),
1189 )
1190 .route("/cms-admin/navigation", get(handlers::navigation_list))
1192 .route(
1193 "/cms-admin/navigation/new",
1194 post(handlers::navigation_create_submit),
1195 )
1196 .route(
1197 "/cms-admin/navigation/{id}/delete",
1198 post(handlers::navigation_delete_submit),
1199 )
1200 .route(
1201 "/cms-admin/navigation/{id}/clone",
1202 post(handlers::navigation_clone_submit),
1203 )
1204 .route(
1205 "/cms-admin/navigation/{id}/save-tree",
1206 post(handlers::navigation_save_tree_submit),
1207 )
1208 .route(
1213 "/cms-admin/navigation/{id}/seed-from-pages",
1214 post(handlers::navigation_seed_from_pages_submit),
1215 )
1216 .route(
1217 "/cms-admin/navigation/{id}/edit",
1218 get(handlers::navigation_edit_form),
1219 )
1220 .route(
1221 "/cms-admin/navigation/{id}/translate",
1222 post(handlers::navigation_translate_submit),
1223 )
1224 .route(
1225 "/cms-admin/navigation/{id}/items",
1226 post(handlers::navigation_item_create),
1227 )
1228 .route(
1229 "/cms-admin/navigation/{menu_id}/items/{id}/delete",
1230 post(handlers::navigation_item_delete),
1231 )
1232 .route("/cms-admin/history", get(handlers::history_page))
1234 .route("/cms-admin/page-types", get(handlers::page_types_dashboard))
1236 .route(
1238 "/cms-admin/page-types/new",
1239 get(handlers::page_type_new_form).post(handlers::page_type_create),
1240 )
1241 .route(
1242 "/cms-admin/page-types/{id}/edit",
1243 get(handlers::page_type_edit_form).post(handlers::page_type_update),
1244 )
1245 .route(
1246 "/cms-admin/page-types/{id}/delete",
1247 post(handlers::page_type_delete),
1248 )
1249 .route(
1251 "/cms-admin/page-types/{id}/build",
1252 get(handlers::page_type_build_form).post(handlers::page_type_build_submit),
1253 )
1254 .route(
1255 "/cms-admin/page-types/{id}/build/publish",
1256 post(handlers::page_type_publish_submit),
1257 )
1258 .route(
1260 "/cms-admin/page-types/{id}/translate",
1261 get(handlers::page_type_translate_form).post(handlers::page_type_translate_submit),
1262 )
1263 .route("/cms-admin/components", get(handlers::components_index))
1265 .route(
1266 "/cms-admin/components/new",
1267 get(handlers::component_new_form).post(handlers::component_create),
1268 )
1269 .route(
1270 "/cms-admin/components/{id}/edit",
1271 get(handlers::component_edit_form).post(handlers::component_update),
1272 )
1273 .route(
1274 "/cms-admin/components/{id}/delete",
1275 post(handlers::component_delete),
1276 )
1277 .route("/cms-admin/settings", get(handlers::settings_page))
1279 .route(
1281 "/cms-admin/settings/branding",
1282 post(handlers::settings_branding_submit),
1283 )
1284 .route(
1289 "/cms-admin/settings/theme",
1290 post(handlers::settings_theme_switch),
1291 )
1292 .route("/cms-admin/me", get(handlers::account_preferences))
1295 .route(
1297 "/cms-admin/__page-chooser",
1298 get(handlers::page_chooser_json),
1299 )
1300 .route(
1302 "/cms-admin/__snippet-chooser",
1303 get(handlers::snippet_chooser_json),
1304 )
1305 .route(
1306 "/cms-admin/__document-chooser",
1307 get(handlers::document_chooser_json),
1308 )
1309 .route(
1312 "/cms-admin/me/notifications",
1313 post(handlers::account_notifications_submit),
1314 )
1315 .route(
1317 "/cms-admin/me/profile",
1318 post(handlers::account_profile_submit),
1319 )
1320 .route(
1322 "/cms-admin/me/language",
1323 post(handlers::account_language_submit),
1324 )
1325 .route("/cms-admin/me/email", post(handlers::account_email_submit))
1327 .route(
1328 "/cms-admin/me/email/confirm",
1329 get(handlers::account_email_confirm),
1330 )
1331 .route(
1332 "/cms-admin/me/password",
1333 post(handlers::account_password_submit),
1334 )
1335 .route(
1338 "/cms-admin/me/mcp-keys",
1339 post(handlers::account_mcp_key_create),
1340 )
1341 .route(
1342 "/cms-admin/me/mcp-keys/{id}/revoke",
1343 post(handlers::account_mcp_key_revoke),
1344 )
1345 .route(
1349 "/cms-admin/users/{id}/mcp-keys",
1350 post(handlers::users_mcp_key_create),
1351 )
1352 .route(
1353 "/cms-admin/users/{id}/mcp-keys/{key_id}/revoke",
1354 post(handlers::users_mcp_key_revoke),
1355 )
1356 .route(
1360 "/__cms-avatar/{user_id}",
1361 get(handlers::account_avatar_serve),
1362 )
1363 .route("/cms-admin/styleguide", get(handlers::styleguide))
1365 .route("/cms-admin/dashboard", get(handlers::dashboard))
1367 .route(
1369 "/cms-admin/dismissibles/{key}",
1370 post(handlers::dismissible_submit),
1371 )
1372 .route("/cms-admin/logout", post(handlers::cms_logout_submit))
1380 .route("/cms-admin/x/{slug}", get(handlers::admin_page_dispatch))
1385 .route_layer(axum::middleware::from_fn(route_perms::gate))
1388 .route_layer(axum::middleware::from_fn(i18n::tenant_overrides_layer))
1390 .route_layer(axum::middleware::from_fn(crate::seed::lazy_seed_layer))
1393 .with_state(state)
1394}
1395
1396async fn redirect_root() -> axum::response::Redirect {
1397 axum::response::Redirect::permanent("/cms-admin/dashboard")
1399}
1400
1401fn immutable_asset<B: axum::response::IntoResponse>(
1406 content_type: &'static str,
1407 body: B,
1408) -> axum::response::Response {
1409 use axum::response::IntoResponse as _;
1410 (
1411 [
1412 (
1413 axum::http::header::CONTENT_TYPE,
1414 axum::http::HeaderValue::from_static(content_type),
1415 ),
1416 (
1417 axum::http::header::CACHE_CONTROL,
1418 axum::http::HeaderValue::from_static("public, max-age=31536000, immutable"),
1419 ),
1420 ],
1421 body,
1422 )
1423 .into_response()
1424}
1425
1426async fn serve_stream_editor_js() -> impl axum::response::IntoResponse {
1428 immutable_asset("text/javascript; charset=utf-8", include_str!("static/stream_editor.js"))
1429}
1430
1431async fn serve_cms_preview_js() -> impl axum::response::IntoResponse {
1435 immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-preview.js"))
1436}
1437
1438async fn serve_block_tree_js() -> impl axum::response::IntoResponse {
1440 immutable_asset("text/javascript; charset=utf-8", include_str!("static/block_tree.js"))
1441}
1442
1443async fn serve_cms_ux_js() -> impl axum::response::IntoResponse {
1449 immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-ux.js"))
1450}
1451
1452async fn serve_menu_builder_js() -> impl axum::response::IntoResponse {
1456 immutable_asset("text/javascript; charset=utf-8", include_str!("static/menu-builder.js"))
1457}
1458
1459async fn serve_form_builder_js() -> impl axum::response::IntoResponse {
1462 immutable_asset("text/javascript; charset=utf-8", include_str!("static/form_builder.js"))
1463}
1464
1465async fn serve_page_type_builder_js() -> impl axum::response::IntoResponse {
1466 immutable_asset("text/javascript; charset=utf-8", include_str!("static/page_type_builder.js"))
1467}
1468
1469async fn serve_page_builder_rules_js() -> impl axum::response::IntoResponse {
1470 immutable_asset("text/javascript; charset=utf-8", include_str!("static/page_builder_rules.js"))
1471}
1472
1473async fn serve_axe_core_js() -> impl axum::response::IntoResponse {
1478 immutable_asset("text/javascript; charset=utf-8", include_str!("static/vendor/axe-core.min.js"))
1479}
1480
1481async fn serve_cms_axe_preview_js() -> impl axum::response::IntoResponse {
1487 immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-axe-preview.js"))
1488}
1489
1490async fn serve_cms_preview_guard_js() -> impl axum::response::IntoResponse {
1495 immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-preview-guard.js"))
1496}
1497
1498const ADMIN_FONT_FILES: &[(&str, &[u8])] = &[
1511 (
1512 "icons-00.woff2",
1513 include_bytes!("static/vendor/fonts/icons-00.woff2"),
1514 ),
1515 (
1516 "text-00.woff2",
1517 include_bytes!("static/vendor/fonts/text-00.woff2"),
1518 ),
1519 (
1520 "text-02.woff2",
1521 include_bytes!("static/vendor/fonts/text-02.woff2"),
1522 ),
1523 (
1524 "text-03.woff2",
1525 include_bytes!("static/vendor/fonts/text-03.woff2"),
1526 ),
1527 (
1528 "text-16.woff2",
1529 include_bytes!("static/vendor/fonts/text-16.woff2"),
1530 ),
1531 (
1532 "text-17.woff2",
1533 include_bytes!("static/vendor/fonts/text-17.woff2"),
1534 ),
1535 (
1536 "text-21.woff2",
1537 include_bytes!("static/vendor/fonts/text-21.woff2"),
1538 ),
1539 (
1540 "text-22.woff2",
1541 include_bytes!("static/vendor/fonts/text-22.woff2"),
1542 ),
1543];
1544
1545async fn serve_admin_fonts_css() -> impl axum::response::IntoResponse {
1548 immutable_asset("text/css; charset=utf-8", include_str!("static/vendor/fonts/fonts.css"))
1549}
1550
1551async fn serve_admin_font_file(axum::extract::Path(file): axum::extract::Path<String>) -> Response {
1554 match ADMIN_FONT_FILES.iter().find(|(name, _)| *name == file) {
1555 Some((_, bytes)) => immutable_asset("font/woff2", *bytes)
1556 .into_response(),
1557 None => (axum::http::StatusCode::NOT_FOUND, "unknown font").into_response(),
1558 }
1559}
1560
1561const ADMIN_BRAND_FILES: &[(&str, &str, &[u8])] = &[
1565 ("logo-light.png", "image/png", include_bytes!("static/brand/logo-light.png")),
1566 ("logo-dark.png", "image/png", include_bytes!("static/brand/logo-dark.png")),
1567 ("icon-light.png", "image/png", include_bytes!("static/brand/icon-light.png")),
1568 ("icon-dark.png", "image/png", include_bytes!("static/brand/icon-dark.png")),
1569 ("favicon.ico", "image/x-icon", include_bytes!("static/brand/favicon.ico")),
1570 ("apple-touch-icon.png", "image/png", include_bytes!("static/brand/apple-touch-icon.png")),
1571];
1572
1573async fn serve_admin_brand_file(axum::extract::Path(file): axum::extract::Path<String>) -> Response {
1574 match ADMIN_BRAND_FILES.iter().find(|(name, _, _)| *name == file) {
1575 Some((_, content_type, bytes)) => immutable_asset(content_type, *bytes).into_response(),
1576 None => (axum::http::StatusCode::NOT_FOUND, "unknown brand file").into_response(),
1577 }
1578}
1579
1580async fn serve_tiptap_bundle_js() -> impl axum::response::IntoResponse {
1585 immutable_asset("text/javascript; charset=utf-8", include_str!("static/vendor/tiptap.bundle.js"))
1586}
1587
1588async fn serve_template_editor_js() -> impl axum::response::IntoResponse {
1592 immutable_asset("text/javascript; charset=utf-8", include_str!("static/template-editor.js"))
1593}
1594
1595async fn serve_codemirror_bundle_js() -> impl axum::response::IntoResponse {
1599 immutable_asset("text/javascript; charset=utf-8", include_str!("static/vendor/codemirror.bundle.js"))
1600}
1601
1602async fn serve_richtext_editor_js() -> impl axum::response::IntoResponse {
1607 immutable_asset("text/javascript; charset=utf-8", include_str!("static/richtext-editor.js"))
1608}
1609
1610const BUNDLED_CMS_CSS: &str = include_str!("static/cms.css");
1614
1615async fn serve_cms_css() -> Response {
1623 let override_path = std::path::Path::new("static/cms_admin/cms.css");
1624 if override_path.exists() {
1625 match std::fs::read_to_string(override_path) {
1626 Ok(source) => {
1627 return (
1628 [
1629 (
1630 axum::http::header::CONTENT_TYPE,
1631 axum::http::HeaderValue::from_static("text/css; charset=utf-8"),
1632 ),
1633 (
1637 axum::http::header::CACHE_CONTROL,
1638 axum::http::HeaderValue::from_static(
1639 "public, max-age=31536000, immutable",
1640 ),
1641 ),
1642 ],
1643 source,
1644 )
1645 .into_response();
1646 }
1647 Err(err) => {
1648 tracing::warn!(
1649 target: "rustango_cms::admin",
1650 error = %err,
1651 path = %override_path.display(),
1652 "failed to read cms.css override; falling back to bundled stylesheet",
1653 );
1654 }
1655 }
1656 }
1657 immutable_asset("text/css; charset=utf-8", BUNDLED_CMS_CSS)
1658 .into_response()
1659}
1660
1661fn cms_asset_version() -> String {
1675 static BUNDLED: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
1676 let bundled = *BUNDLED.get_or_init(|| {
1677 let mut h: u64 = 0xcbf29ce4_84222325;
1680 let mut feed_bytes = |bytes: &[u8]| {
1681 for &b in bytes {
1682 h ^= u64::from(b);
1683 h = h.wrapping_mul(0x0000_0100_0000_01b3);
1684 }
1685 };
1686 for (_, _, bytes) in ADMIN_BRAND_FILES {
1688 feed_bytes(bytes);
1689 }
1690 let mut feed = |s: &str| feed_bytes(s.as_bytes());
1691 feed(BUNDLED_CMS_CSS);
1692 feed(include_str!("static/cms-ux.js"));
1693 feed(include_str!("static/stream_editor.js"));
1694 feed(include_str!("static/richtext-editor.js"));
1695 feed(include_str!("static/block_tree.js"));
1699 feed(include_str!("static/page_type_builder.js"));
1700 feed(include_str!("static/form_builder.js"));
1701 feed(include_str!("static/menu-builder.js"));
1702 feed(include_str!("static/cms-axe-preview.js"));
1703 feed(include_str!("static/cms-preview-guard.js"));
1704 feed(include_str!("static/cms-preview.js"));
1705 feed(include_str!("static/page_builder_rules.js"));
1706 h
1707 });
1708 if let Ok(meta) = std::fs::metadata("static/cms_admin/cms.css") {
1709 let mtime = meta
1710 .modified()
1711 .ok()
1712 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1713 .map_or(0, |d| d.as_secs());
1714 return format!("{bundled:x}.{mtime:x}.{:x}", meta.len());
1715 }
1716 format!("{bundled:x}")
1717}
1718
1719struct CmsAssetVersionFn;
1721
1722impl tera::Function for CmsAssetVersionFn {
1723 fn call(
1724 &self,
1725 _args: &std::collections::HashMap<String, tera::Value>,
1726 ) -> tera::Result<tera::Value> {
1727 Ok(tera::Value::String(cms_asset_version()))
1728 }
1729}
1730
1731struct JsonScriptFilter;
1740
1741impl tera::Filter for JsonScriptFilter {
1742 fn filter(
1743 &self,
1744 value: &tera::Value,
1745 _args: &std::collections::HashMap<String, tera::Value>,
1746 ) -> tera::Result<tera::Value> {
1747 Ok(tera::Value::String(json_script(value)))
1748 }
1749
1750 fn is_safe(&self) -> bool {
1751 true
1752 }
1753}
1754
1755fn json_script(value: &tera::Value) -> String {
1756 serde_json::to_string(value)
1757 .unwrap_or_else(|_| "null".to_owned())
1758 .replace('<', "\\u003c")
1759 .replace('>', "\\u003e")
1760 .replace('&', "\\u0026")
1761 .replace('\'', "\\u0027")
1762}
1763
1764pub fn register_templates(tera: &mut Tera) -> Result<(), tera::Error> {
1808 crate::urls::register_tera_helpers(tera);
1809 tera.register_function("cms_asset_version", CmsAssetVersionFn);
1812 tera.register_filter("json_script", JsonScriptFilter);
1813 rustango::i18n::tera_tags::register(tera, i18n::cached_translator().clone());
1818 i18n::register_tera_bindings(tera);
1819 tera.register_function(
1831 "get_env",
1832 |_args: &std::collections::HashMap<String, tera::Value>| -> tera::Result<tera::Value> {
1833 Err(tera::Error::msg(
1834 "get_env is disabled in CMS templates for security reasons",
1835 ))
1836 },
1837 );
1838 tera.add_raw_templates(vec![
1839 (
1840 "rcms_admin/_base.html",
1841 include_str!("templates/_base.html"),
1842 ),
1843 (
1844 "rcms_admin/_auth_layout.html",
1845 include_str!("templates/_auth_layout.html"),
1846 ),
1847 (
1850 "rcms_admin/_brand_icons.html",
1851 include_str!("templates/_brand_icons.html"),
1852 ),
1853 (
1856 "rcms_admin/_list_base.html",
1857 include_str!("templates/_list_base.html"),
1858 ),
1859 (
1866 "rcms_admin/_stream_widget.html",
1867 "{% import \"rcms_admin/_widget.html\" as widget %}{{ widget::render(w=w) }}",
1868 ),
1869 (
1870 "rcms_admin/member_login.html",
1871 include_str!("templates/member_login.html"),
1872 ),
1873 (
1874 "rcms_admin/member_signup.html",
1875 include_str!("templates/member_signup.html"),
1876 ),
1877 (
1878 "rcms_admin/_mcp_keys_card.html",
1879 include_str!("templates/_mcp_keys_card.html"),
1880 ),
1881 (
1882 "rcms_admin/_pagination.html",
1883 include_str!("templates/_pagination.html"),
1884 ),
1885 (
1886 "rcms_admin/_preview_pane.html",
1887 include_str!("templates/_preview_pane.html"),
1888 ),
1889 (
1890 "rcms_admin/notifications.html",
1891 include_str!("templates/notifications.html"),
1892 ),
1893 ("rcms_admin/sites.html", include_str!("templates/sites.html")),
1894 (
1895 "rcms_admin/_widget.html",
1896 include_str!("templates/_widget.html"),
1897 ),
1898 (
1899 "rcms_admin/_widget_group.html",
1900 include_str!("templates/_widget_group.html"),
1901 ),
1902 (
1903 "rcms_admin/_permissions_tab.html",
1904 include_str!("templates/_permissions_tab.html"),
1905 ),
1906 (
1907 "rcms_admin/page_list.html",
1908 include_str!("templates/page_list.html"),
1909 ),
1910 (
1911 "rcms_admin/page_form.html",
1912 include_str!("templates/page_form.html"),
1913 ),
1914 (
1915 "rcms_admin/page_type_picker.html",
1916 include_str!("templates/page_type_picker.html"),
1917 ),
1918 (
1919 "rcms_admin/library_list.html",
1920 include_str!("templates/library_list.html"),
1921 ),
1922 (
1923 "rcms_admin/snippet_form.html",
1924 include_str!("templates/snippet_form.html"),
1925 ),
1926 (
1927 "rcms_admin/form_builder.html",
1928 include_str!("templates/form_builder.html"),
1929 ),
1930 (
1931 "rcms_admin/form_submissions.html",
1932 include_str!("templates/form_submissions.html"),
1933 ),
1934 (
1935 "rcms_admin/forms_list.html",
1936 include_str!("templates/forms_list.html"),
1937 ),
1938 (
1939 "rcms_admin/form_translate.html",
1940 include_str!("templates/form_translate.html"),
1941 ),
1942 (
1943 "rcms_admin/page_type_translate.html",
1944 include_str!("templates/page_type_translate.html"),
1945 ),
1946 (
1947 "rcms_admin/media_list.html",
1948 include_str!("templates/media_list.html"),
1949 ),
1950 (
1951 "rcms_admin/media_upload.html",
1952 include_str!("templates/media_upload.html"),
1953 ),
1954 (
1955 "rcms_admin/model_admin_list.html",
1956 include_str!("templates/model_admin_list.html"),
1957 ),
1958 (
1959 "rcms_admin/report.html",
1960 include_str!("templates/report.html"),
1961 ),
1962 (
1963 "rcms_admin/locale_list.html",
1964 include_str!("templates/locale_list.html"),
1965 ),
1966 (
1967 "rcms_admin/locale_form.html",
1968 include_str!("templates/locale_form.html"),
1969 ),
1970 (
1971 "rcms_admin/sso_provider_list.html",
1972 include_str!("templates/sso_provider_list.html"),
1973 ),
1974 (
1975 "rcms_admin/sso_provider_form.html",
1976 include_str!("templates/sso_provider_form.html"),
1977 ),
1978 (
1979 "rcms_admin/workflow_list.html",
1980 include_str!("templates/workflow_list.html"),
1981 ),
1982 (
1983 "rcms_admin/workflow_form.html",
1984 include_str!("templates/workflow_form.html"),
1985 ),
1986 (
1987 "rcms_admin/history_diff.html",
1988 include_str!("templates/history_diff.html"),
1989 ),
1990 (
1991 "rcms_admin/admin_search.html",
1992 include_str!("templates/admin_search.html"),
1993 ),
1994 (
1995 "rcms_admin/analytics.html",
1996 include_str!("templates/analytics.html"),
1997 ),
1998 (
1999 "rcms_admin/aging_pages.html",
2000 include_str!("templates/aging_pages.html"),
2001 ),
2002 (
2003 "rcms_admin/locked_pages.html",
2004 include_str!("templates/locked_pages.html"),
2005 ),
2006 (
2007 "rcms_admin/workflow_report.html",
2008 include_str!("templates/workflow_report.html"),
2009 ),
2010 (
2011 "rcms_admin/revisions_report.html",
2012 include_str!("templates/revisions_report.html"),
2013 ),
2014 (
2015 "rcms_admin/scheduled_report.html",
2016 include_str!("templates/scheduled_report.html"),
2017 ),
2018 (
2019 "rcms_admin/search_promotions_report.html",
2020 include_str!("templates/search_promotions_report.html"),
2021 ),
2022 (
2023 "rcms_admin/search_promotion_edit.html",
2024 include_str!("templates/search_promotion_edit.html"),
2025 ),
2026 (
2027 "rcms_admin/styleguide.html",
2028 include_str!("templates/styleguide.html"),
2029 ),
2030 (
2031 "rcms_admin/dashboard.html",
2032 include_str!("templates/dashboard.html"),
2033 ),
2034 (
2035 "rcms_admin/redirect_import.html",
2036 include_str!("templates/redirect_import.html"),
2037 ),
2038 (
2039 "rcms_admin/snippet_import.html",
2040 include_str!("templates/snippet_import.html"),
2041 ),
2042 (
2043 "rcms_admin/site_settings_list.html",
2044 include_str!("templates/site_settings_list.html"),
2045 ),
2046 (
2047 "rcms_admin/template_list.html",
2048 include_str!("templates/template_list.html"),
2049 ),
2050 (
2051 "rcms_admin/template_form.html",
2052 include_str!("templates/template_form.html"),
2053 ),
2054 (
2055 "rcms_admin/page_type_template_form.html",
2056 include_str!("templates/page_type_template_form.html"),
2057 ),
2058 (
2059 "rcms_admin/site_setting_form.html",
2060 include_str!("templates/site_setting_form.html"),
2061 ),
2062 (
2066 "rcms/view_password.html",
2067 include_str!("templates/view_password.html"),
2068 ),
2069 (
2070 "rcms_admin/redirect_list.html",
2071 include_str!("templates/redirect_list.html"),
2072 ),
2073 (
2074 "rcms_admin/redirect_form.html",
2075 include_str!("templates/redirect_form.html"),
2076 ),
2077 (
2078 "rcms_admin/settings.html",
2079 include_str!("templates/settings.html"),
2080 ),
2081 (
2082 "rcms_admin/history.html",
2083 include_str!("templates/history.html"),
2084 ),
2085 (
2086 "rcms_admin/navigation_list.html",
2087 include_str!("templates/navigation_list.html"),
2088 ),
2089 (
2090 "rcms_admin/navigation_edit.html",
2091 include_str!("templates/navigation_edit.html"),
2092 ),
2093 (
2094 "rcms_admin/page_types.html",
2095 include_str!("templates/page_types.html"),
2096 ),
2097 (
2098 "rcms_admin/page_type_builder.html",
2099 include_str!("templates/page_type_builder.html"),
2100 ),
2101 (
2102 "rcms_admin/components_list.html",
2103 include_str!("templates/components_list.html"),
2104 ),
2105 (
2106 "rcms_admin/schema_page.html",
2107 include_str!("templates/schema_page.html"),
2108 ),
2109 (
2110 "rcms_admin/page_type_form.html",
2111 include_str!("templates/page_type_form.html"),
2112 ),
2113 (
2114 "rcms_admin/component_builder.html",
2115 include_str!("templates/component_builder.html"),
2116 ),
2117 (
2118 "rcms_admin/users_list.html",
2119 include_str!("templates/users_list.html"),
2120 ),
2121 (
2122 "rcms_admin/security_log.html",
2123 include_str!("templates/security_log.html"),
2124 ),
2125 (
2126 "rcms_admin/user_form.html",
2127 include_str!("templates/user_form.html"),
2128 ),
2129 (
2130 "rcms_admin/roles_list.html",
2131 include_str!("templates/roles_list.html"),
2132 ),
2133 (
2134 "rcms_admin/permissions_overview.html",
2135 include_str!("templates/permissions_overview.html"),
2136 ),
2137 (
2138 "rcms_admin/role_form.html",
2139 include_str!("templates/role_form.html"),
2140 ),
2141 (
2142 "rcms_admin/media_unused.html",
2143 include_str!("templates/media_unused.html"),
2144 ),
2145 (
2146 "rcms_admin/media_edit.html",
2147 include_str!("templates/media_edit.html"),
2148 ),
2149 (
2150 "rcms_admin/collection_permissions.html",
2151 include_str!("templates/collection_permissions.html"),
2152 ),
2153 (
2154 "rcms_admin/collections_list.html",
2155 include_str!("templates/collections_list.html"),
2156 ),
2157 (
2159 "rcms_admin/taxonomies_list.html",
2160 include_str!("templates/taxonomies_list.html"),
2161 ),
2162 (
2163 "rcms_admin/category_tree.html",
2164 include_str!("templates/category_tree.html"),
2165 ),
2166 (
2167 "rcms_admin/category_form.html",
2168 include_str!("templates/category_form.html"),
2169 ),
2170 ("login.html", include_str!("templates/login.html")),
2176 (
2177 "rcms_admin/password_reset_request.html",
2178 include_str!("templates/password_reset_request.html"),
2179 ),
2180 (
2181 "rcms_admin/password_reset_sent.html",
2182 include_str!("templates/password_reset_sent.html"),
2183 ),
2184 (
2185 "rcms_admin/password_reset_confirm.html",
2186 include_str!("templates/password_reset_confirm.html"),
2187 ),
2188 (
2189 "rcms_admin/password_reset_done.html",
2190 include_str!("templates/password_reset_done.html"),
2191 ),
2192 (
2193 "rcms_admin/no_access.html",
2194 include_str!("templates/no_access.html"),
2195 ),
2196 (
2197 "rcms_admin/account_preferences.html",
2198 include_str!("templates/account_preferences.html"),
2199 ),
2200 (
2201 "rcms_admin/_breadcrumbs.html",
2202 include_str!("templates/_breadcrumbs.html"),
2203 ),
2204 (
2210 "blocks/heading.html",
2211 include_str!("templates/blocks/heading.html"),
2212 ),
2213 (
2214 "blocks/paragraph.html",
2215 include_str!("templates/blocks/paragraph.html"),
2216 ),
2217 (
2218 "blocks/image.html",
2219 include_str!("templates/blocks/image.html"),
2220 ),
2221 (
2222 "blocks/quote.html",
2223 include_str!("templates/blocks/quote.html"),
2224 ),
2225 (
2226 "blocks/embed.html",
2227 include_str!("templates/blocks/embed.html"),
2228 ),
2229 (
2230 "blocks/code.html",
2231 include_str!("templates/blocks/code.html"),
2232 ),
2233 (
2235 "blocks/text.html",
2236 include_str!("templates/blocks/text.html"),
2237 ),
2238 (
2239 "blocks/boolean.html",
2240 include_str!("templates/blocks/boolean.html"),
2241 ),
2242 (
2243 "blocks/date.html",
2244 include_str!("templates/blocks/date.html"),
2245 ),
2246 (
2247 "blocks/datetime.html",
2248 include_str!("templates/blocks/datetime.html"),
2249 ),
2250 (
2251 "blocks/email.html",
2252 include_str!("templates/blocks/email.html"),
2253 ),
2254 ("blocks/url.html", include_str!("templates/blocks/url.html")),
2255 (
2256 "blocks/integer.html",
2257 include_str!("templates/blocks/integer.html"),
2258 ),
2259 (
2260 "blocks/choice.html",
2261 include_str!("templates/blocks/choice.html"),
2262 ),
2263 (
2264 "blocks/table.html",
2265 include_str!("templates/blocks/table.html"),
2266 ),
2267 (
2269 "blocks/float.html",
2270 include_str!("templates/blocks/float.html"),
2271 ),
2272 (
2273 "blocks/decimal.html",
2274 include_str!("templates/blocks/decimal.html"),
2275 ),
2276 (
2277 "blocks/regex.html",
2278 include_str!("templates/blocks/regex.html"),
2279 ),
2280 (
2281 "blocks/rich_text.html",
2282 include_str!("templates/blocks/rich_text.html"),
2283 ),
2284 (
2285 "blocks/typed_table_row.html",
2286 include_str!("templates/blocks/typed_table_row.html"),
2287 ),
2288 (
2289 "blocks/typed_table.html",
2290 include_str!("templates/blocks/typed_table.html"),
2291 ),
2292 (
2293 "blocks/time.html",
2294 include_str!("templates/blocks/time.html"),
2295 ),
2296 (
2297 "blocks/multiple_choice.html",
2298 include_str!("templates/blocks/multiple_choice.html"),
2299 ),
2300 (
2301 "blocks/static.html",
2302 include_str!("templates/blocks/static.html"),
2303 ),
2304 (
2305 "blocks/raw_html.html",
2306 include_str!("templates/blocks/raw_html.html"),
2307 ),
2308 (
2309 "blocks/page_chooser.html",
2310 include_str!("templates/blocks/page_chooser.html"),
2311 ),
2312 (
2313 "blocks/snippet_chooser.html",
2314 include_str!("templates/blocks/snippet_chooser.html"),
2315 ),
2316 (
2317 "blocks/document_chooser.html",
2318 include_str!("templates/blocks/document_chooser.html"),
2319 ),
2320 ])?;
2321
2322 if !tera.get_template_names().any(|n| n == "error_page.html") {
2329 tera.add_raw_template("error_page.html", include_str!("templates/error_page.html"))?;
2330 }
2331
2332 let override_root = std::path::PathBuf::from("templates/cms_admin");
2337 if override_root.is_dir() {
2338 let count = load_template_overrides(&override_root, "", tera)?;
2339 if count > 0 {
2340 tracing::info!(
2341 target: "rustango_cms::admin",
2342 count,
2343 path = %override_root.display(),
2344 "loaded admin template overrides",
2345 );
2346 }
2347 }
2348 Ok(())
2349}
2350
2351fn load_template_overrides(
2363 dir: &std::path::Path,
2364 prefix: &str,
2365 tera: &mut Tera,
2366) -> Result<usize, tera::Error> {
2367 let mut count = 0;
2368 let entries = std::fs::read_dir(dir)
2369 .map_err(|e| tera::Error::msg(format!("read_dir {}: {e}", dir.display())))?;
2370 for entry in entries {
2371 let entry = entry
2372 .map_err(|e| tera::Error::msg(format!("read_dir entry in {}: {e}", dir.display())))?;
2373 let path = entry.path();
2374 let name = match entry.file_name().into_string() {
2375 Ok(n) => n,
2376 Err(_) => continue,
2377 };
2378 if path.is_dir() {
2379 let nested_prefix = if prefix.is_empty() {
2380 name.clone()
2381 } else {
2382 format!("{prefix}/{name}")
2383 };
2384 count += load_template_overrides(&path, &nested_prefix, tera)?;
2385 } else if path.extension().and_then(|e| e.to_str()) == Some("html") {
2386 let template_name = derive_override_template_name(prefix, &name);
2387 let source = std::fs::read_to_string(&path)
2388 .map_err(|e| tera::Error::msg(format!("read {}: {e}", path.display())))?;
2389 tera.add_raw_template(&template_name, &source)?;
2390 tracing::info!(
2391 target: "rustango_cms::admin",
2392 path = %path.display(),
2393 template = %template_name,
2394 "registered admin template override",
2395 );
2396 count += 1;
2397 }
2398 }
2399 Ok(count)
2400}
2401
2402fn derive_override_template_name(prefix: &str, file_name: &str) -> String {
2408 if prefix.is_empty() {
2409 match file_name {
2413 "_auth_layout.html" => "rcms_admin/_auth_layout.html".to_owned(),
2414 other => other.to_owned(),
2415 }
2416 } else {
2417 format!("{prefix}/{file_name}")
2418 }
2419}
2420
2421#[derive(Debug, thiserror::Error)]
2424pub(crate) enum AdminError {
2425 #[error(transparent)]
2426 Tree(#[from] TreeError),
2427 #[error(transparent)]
2428 Exec(#[from] rustango::sql::ExecError),
2429 #[error(transparent)]
2430 Sqlx(#[from] rustango::sql::sqlx::Error),
2431 #[error(transparent)]
2432 Tera(#[from] tera::Error),
2433 #[error("page {0} not found")]
2434 NotFound(i64),
2435 #[error("upload failed: {0}")]
2436 Upload(String),
2437 #[error("{0}")]
2438 Validation(String),
2439}
2440
2441impl IntoResponse for AdminError {
2442 fn into_response(self) -> Response {
2443 let status = match &self {
2444 AdminError::NotFound(_) => StatusCode::NOT_FOUND,
2445 AdminError::Tree(TreeError::DisallowedChildType { .. })
2446 | AdminError::Tree(TreeError::DisallowedParentType { .. })
2447 | AdminError::Tree(TreeError::CycleAttempt) => StatusCode::BAD_REQUEST,
2448 AdminError::Upload(_) => StatusCode::BAD_REQUEST,
2449 AdminError::Validation(_) => StatusCode::BAD_REQUEST,
2450 _ => StatusCode::INTERNAL_SERVER_ERROR,
2451 };
2452 let mut chain = self.to_string();
2453 let mut src: Option<&dyn std::error::Error> = std::error::Error::source(&self);
2454 while let Some(s) = src {
2455 chain.push_str("\n caused by: ");
2456 chain.push_str(&s.to_string());
2457 src = s.source();
2458 }
2459 if status != StatusCode::INTERNAL_SERVER_ERROR {
2460 return (status, chain).into_response();
2462 }
2463 let reference = crate::mcp::mint_uuid4();
2467 tracing::error!(target: "rustango_cms::admin", error_ref = %reference, "{chain}");
2468 (status, format!("Internal server error (ref {reference})")).into_response()
2469 }
2470}
2471
2472#[derive(Debug, Deserialize)]
2474pub struct PageForm {
2475 pub title: String,
2476 pub slug: String,
2477 pub page_type_id: i64,
2478 pub status: String,
2479 #[serde(rename = "_action", default)]
2484 pub action: String,
2485 #[serde(default)]
2486 pub seo_title: String,
2487 #[serde(default)]
2488 pub seo_description: String,
2489 #[serde(default)]
2490 pub robots_index: Option<String>,
2491 #[serde(default)]
2492 pub sitemap_priority: Option<f32>,
2493 #[serde(default)]
2497 pub show_in_menus: Option<String>,
2498 #[serde(default)]
2502 pub parent_id: Option<i64>,
2503 #[serde(default, deserialize_with = "deserialize_present_optional_i64")]
2508 pub theme_id: Option<Option<i64>>,
2509 #[serde(default)]
2515 pub go_live_at: Option<String>,
2516 #[serde(default)]
2518 pub expire_at: Option<String>,
2519 #[serde(default)]
2524 pub preview_path: String,
2525 #[serde(default)]
2528 pub template_override: String,
2529 #[serde(default)]
2533 pub og_title: String,
2534 #[serde(default)]
2535 pub og_description: String,
2536 #[serde(default, deserialize_with = "deserialize_optional_i64")]
2537 pub og_image_media_id: Option<i64>,
2538 #[serde(default)]
2539 pub twitter_card: Option<String>,
2540 #[serde(default)]
2543 pub tags: Option<String>,
2544 #[serde(default)]
2546 pub categories: Option<String>,
2547}
2548
2549pub(crate) fn deserialize_optional_i64<'de, D>(deserializer: D) -> Result<Option<i64>, D::Error>
2553where
2554 D: serde::Deserializer<'de>,
2555{
2556 use serde::Deserialize as _;
2557 let s = String::deserialize(deserializer)?;
2558 if s.is_empty() || s == "0" {
2559 return Ok(None);
2560 }
2561 s.parse::<i64>().map(Some).map_err(serde::de::Error::custom)
2562}
2563
2564fn deserialize_present_optional_i64<'de, D>(deserializer: D) -> Result<Option<Option<i64>>, D::Error>
2567where
2568 D: serde::Deserializer<'de>,
2569{
2570 deserialize_optional_i64(deserializer).map(Some)
2571}
2572
2573impl PageForm {
2574 fn parsed_status(&self) -> PageStatus {
2578 match self.status.as_str() {
2579 "published" => PageStatus::Published,
2580 "scheduled" => PageStatus::Scheduled,
2581 "archived" => PageStatus::Archived,
2582 _ => PageStatus::Draft,
2583 }
2584 }
2585
2586 fn parsed_robots_index(&self) -> bool {
2589 self.robots_index.is_some()
2590 }
2591
2592 fn parsed_sitemap_priority(&self) -> f32 {
2593 self.sitemap_priority.unwrap_or(0.5)
2594 }
2595
2596 fn parsed_show_in_menus(&self) -> bool {
2597 self.show_in_menus.is_some()
2598 }
2599
2600 fn parsed_go_live_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
2606 parse_datetime_local(self.go_live_at.as_deref())
2607 }
2608
2609 fn parsed_expire_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
2610 parse_datetime_local(self.expire_at.as_deref())
2611 }
2612}
2613
2614fn parse_datetime_local(raw: Option<&str>) -> Option<chrono::DateTime<chrono::Utc>> {
2615 let raw = raw?.trim();
2616 if raw.is_empty() {
2617 return None;
2618 }
2619 if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(raw) {
2622 return Some(dt.with_timezone(&chrono::Utc));
2623 }
2624 if let Some(utc) = raw.strip_suffix('Z') {
2625 return parse_datetime_local(Some(utc));
2626 }
2627 chrono::NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M")
2630 .or_else(|_| chrono::NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M:%S"))
2631 .ok()
2632 .map(|naive| chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(naive, chrono::Utc))
2633}
2634
2635#[cfg(test)]
2636mod datetime_input_tests {
2637 use super::parse_datetime_local;
2638
2639 #[test]
2642 fn utc_offset_and_bare_values_parse_to_the_same_instant() {
2643 let want = chrono::DateTime::parse_from_rfc3339("2026-12-01T12:00:00Z")
2644 .unwrap()
2645 .with_timezone(&chrono::Utc);
2646 for raw in ["2026-12-01T12:00Z", "2026-12-01T12:00:00Z", "2026-12-01T09:00:00-03:00", "2026-12-01T12:00", " 2026-12-01T12:00:00 "] {
2647 assert_eq!(parse_datetime_local(Some(raw)), Some(want), "{raw}");
2648 }
2649 assert_eq!(parse_datetime_local(Some("")), None);
2650 assert_eq!(parse_datetime_local(Some("tomorrow")), None);
2651 }
2652}
2653
2654#[cfg(test)]
2655mod admin_error_tests {
2656 use super::AdminError;
2657 use axum::response::IntoResponse as _;
2658
2659 async fn body(e: AdminError) -> (u16, String) {
2660 let resp = e.into_response();
2661 let status = resp.status().as_u16();
2662 let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16).await.expect("body");
2663 (status, String::from_utf8(bytes.to_vec()).expect("utf8"))
2664 }
2665
2666 #[tokio::test]
2669 async fn server_errors_hide_their_cause_and_client_errors_do_not() {
2670 let tera_err = tera::Tera::one_off("{{ secret_column | nope }}", &tera::Context::new(), false)
2671 .expect_err("bad template");
2672 let (status, text) = body(AdminError::Tera(tera_err)).await;
2673 assert_eq!(status, 500);
2674 assert!(text.starts_with("Internal server error (ref "), "{text}");
2675 assert!(!text.contains("secret_column") && !text.contains("nope"), "{text}");
2676
2677 let (status, text) = body(AdminError::Validation("slug is taken".into())).await;
2678 assert_eq!(status, 400);
2679 assert!(text.contains("slug is taken"));
2680 }
2681}
2682
2683#[cfg(test)]
2684mod template_shape_tests {
2685 #[test]
2688 fn json_script_cannot_close_the_script_element() {
2689 let hostile = serde_json::json!([{
2690 "name": "</script><script>alert('x')</script> & <!--",
2691 }]);
2692 let mut tera = tera::Tera::default();
2693 super::register_templates(&mut tera).expect("register");
2694 tera.add_raw_template("t", "<script>const X = {{ v | json_script }};</script>")
2695 .expect("template");
2696 let mut ctx = tera::Context::new();
2697 ctx.insert("v", &hostile);
2698 let out = tera.render("t", &ctx).expect("render");
2699 let body = out
2700 .strip_prefix("<script>const X = ")
2701 .and_then(|r| r.strip_suffix(";</script>"))
2702 .expect("one script element");
2703 assert!(!body.contains('<') && !body.contains('>') && !body.contains('\''), "{body}");
2704 let back: serde_json::Value = serde_json::from_str(body).expect("still JSON");
2705 assert_eq!(back, hostile);
2706 }
2707
2708 #[test]
2711 fn no_admin_template_inlines_raw_json() {
2712 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/admin/templates");
2713 let offenders: Vec<String> = std::fs::read_dir(&dir)
2714 .expect("read templates dir")
2715 .filter_map(|e| {
2716 let path = e.expect("dir entry").path();
2717 let src = std::fs::read_to_string(&path).ok()?;
2718 src.contains("json_encode | safe")
2719 .then(|| path.file_name().unwrap().to_string_lossy().to_string())
2720 })
2721 .collect();
2722 assert!(offenders.is_empty(), "use `| json_script` instead: {offenders:?}");
2723 }
2724
2725 #[test]
2736 fn page_descriptions_come_from_the_shared_intro_card() {
2737 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/admin/templates");
2738 let mut offenders = Vec::new();
2739 let mut checked = 0;
2740 for entry in std::fs::read_dir(&dir).expect("read templates dir") {
2741 let path = entry.expect("dir entry").path();
2742 if path.extension().and_then(|e| e.to_str()) != Some("html") {
2743 continue;
2744 }
2745 let src = std::fs::read_to_string(&path).expect("read template");
2746 let name = path.file_name().unwrap().to_string_lossy().to_string();
2747 if src.contains("rcms_admin/_list_base.html") {
2748 checked += 1;
2750 continue;
2751 }
2752 let Some(rest) = src.split_once("{% block content %}") else {
2753 continue;
2754 };
2755 checked += 1;
2756 let head = rest.1.trim_start();
2757 if head.starts_with("<p class=\"rcms-hint") {
2758 offenders.push(format!(
2759 "{name}: bare <p class=\"rcms-hint\"> opens the content \
2760 column — extend rcms_admin/_list_base.html and put the \
2761 prose in {{% block description %}}"
2762 ));
2763 } else if rest
2764 .1
2765 .contains("<div class=\"rcms-card\">\n <p class=\"rcms-hint")
2766 {
2767 offenders.push(format!(
2771 "{name}: hand-rolled intro card — extend \
2772 rcms_admin/_list_base.html instead"
2773 ));
2774 }
2775 }
2776 assert!(
2777 checked > 40,
2778 "expected to scan most admin templates, scanned {checked} — \
2779 the `{{% block content %}}` probe is broken"
2780 );
2781 assert!(
2782 offenders.is_empty(),
2783 "{} page(s) don't use the shared intro card:\n{}",
2784 offenders.len(),
2785 offenders.join("\n")
2786 );
2787 }
2788
2789 #[test]
2798 fn get_env_is_disabled_in_the_render_engine() {
2799 let secret = std::env::var("CARGO_PKG_NAME").expect("cargo sets CARGO_PKG_NAME");
2800 let mut tera = tera::Tera::default();
2801 super::register_templates(&mut tera).expect("register_templates");
2802 tera.add_raw_template("ssti.html", r#"{{ get_env(name="CARGO_PKG_NAME") }}"#)
2803 .expect("add template");
2804 match tera.render("ssti.html", &tera::Context::new()) {
2805 Err(_) => {}
2807 Ok(out) => assert!(
2810 !out.contains(&secret),
2811 "get_env leaked the process environment into a template: {out}"
2812 ),
2813 }
2814 }
2815}