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;
56
57pub mod chooser;
58mod handlers;
59mod i18n;
60pub(crate) mod members;
61pub use i18n::extend_ui_catalog;
65pub mod model_admin;
66pub mod pagination;
67pub mod report;
68pub mod resources;
69mod route_perms;
70pub(crate) mod notifications;
71pub(crate) mod sites;
72pub(crate) mod template_editor;
73pub use template_editor::CODENAME as TEMPLATE_EDIT_CODENAME;
76pub use notifications::CODENAME as NOTIFICATION_MANAGE_CODENAME;
79pub use sites::CODENAME as SITE_MANAGE_CODENAME;
82pub(crate) use template_editor::offerable as template_offerable;
85pub use handlers::ListQuery;
86pub(crate) use handlers::{
88 allowed_children_for, allowed_root_types, apply_page_edit, dedup_slug_under_parent,
89 media_picker_payload, slugify, store_media, upsert_page_translations, MediaPickerQuery,
90 PageEditActor, PageEditOutcome, PageEditRefusal,
91};
92
93#[derive(Clone)]
99pub(crate) struct AdminState {
100 pub(crate) tera: Arc<Tera>,
101 pub(crate) signing_secret: Arc<Vec<u8>>,
107 pub(crate) cache_invalidator: Arc<dyn crate::cache_invalidate::PageCacheInvalidator>,
114 pub(crate) mailer: Option<Arc<dyn rustango::email::Mailer>>,
119 pub(crate) mailer_from: Arc<String>,
123}
124
125pub fn router(tera: Arc<Tera>) -> Router {
136 let secret = load_or_generate_signing_secret(&std::path::PathBuf::from(
137 "./var/.rustango_cms_signing.key",
138 ));
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 = load_or_generate_signing_secret(&std::path::PathBuf::from(
157 "./var/.rustango_cms_signing.key",
158 ));
159 crate::task_queue::set_default_invalidator(Arc::clone(&invalidator));
161 router_with_state(AdminState {
162 tera,
163 signing_secret: Arc::new(secret),
164 cache_invalidator: invalidator,
165 mailer: None,
166 mailer_from: Arc::new(String::new()),
167 })
168}
169
170pub fn router_with_mailer(
176 tera: Arc<Tera>,
177 invalidator: Arc<dyn crate::cache_invalidate::PageCacheInvalidator>,
178 mailer: Arc<dyn rustango::email::Mailer>,
179 from_addr: impl Into<String>,
180) -> Router {
181 let secret = load_or_generate_signing_secret(&std::path::PathBuf::from(
182 "./var/.rustango_cms_signing.key",
183 ));
184 crate::task_queue::set_default_invalidator(Arc::clone(&invalidator));
186 router_with_state(AdminState {
187 tera,
188 signing_secret: Arc::new(secret),
189 cache_invalidator: invalidator,
190 mailer: Some(mailer),
191 mailer_from: Arc::new(from_addr.into()),
192 })
193}
194
195pub fn public_router(tera: Arc<Tera>) -> Router {
211 public_router_inner(tera, None, String::new())
212}
213
214pub fn public_router_with_mailer(
219 tera: Arc<Tera>,
220 mailer: Arc<dyn rustango::email::Mailer>,
221 from_addr: impl Into<String>,
222) -> Router {
223 public_router_inner(tera, Some(mailer), from_addr.into())
224}
225
226fn public_router_inner(
227 tera: Arc<Tera>,
228 mailer: Option<Arc<dyn rustango::email::Mailer>>,
229 mailer_from: String,
230) -> Router {
231 let secret = load_or_generate_signing_secret(&std::path::PathBuf::from(
232 "./var/.rustango_cms_signing.key",
233 ));
234 let state = AdminState {
235 tera,
236 signing_secret: Arc::new(secret),
237 cache_invalidator: crate::cache_invalidate::noop(),
238 mailer,
239 mailer_from: Arc::new(mailer_from),
240 };
241 Router::new()
242 .route(
243 "/cms-admin/password-reset",
244 get(handlers::password_reset_request_form)
245 .post(handlers::password_reset_request_submit),
246 )
247 .route(
248 "/cms-admin/password-reset/confirm",
249 get(handlers::password_reset_confirm_form)
250 .post(handlers::password_reset_confirm_submit),
251 )
252 .route("/login", get(handlers::cms_login_form))
257 .route(
264 "/members/login",
265 get(members::member_login_form).post(members::member_login_submit),
266 )
267 .route(
268 "/members/signup",
269 get(members::member_signup_form).post(members::member_signup_submit),
270 )
271 .route("/members/logout", post(members::member_logout))
272 .route(
277 "/__cms-branding/logo",
278 get(handlers::settings_branding_serve_logo),
279 )
280 .route(
281 "/__cms-branding/favicon",
282 get(handlers::settings_branding_serve_favicon),
283 )
284 .route("/cms-admin/no-access", get(handlers::no_access_page))
288 .route("/cms-admin/static/cms.css", get(serve_cms_css))
292 .route("/cms-admin/static/fonts.css", get(serve_admin_fonts_css))
303 .route(
304 "/cms-admin/static/vendor/fonts/{file}",
305 get(serve_admin_font_file),
306 )
307 .route("/cms-admin/static/brand/{file}", get(serve_admin_brand_file))
311 .route("/cms-admin/static/cms-ux.js", get(serve_cms_ux_js))
312 .route(
313 "/cms-admin/static/stream_editor.js",
314 get(serve_stream_editor_js),
315 )
316 .route("/cms-admin/static/block_tree.js", get(serve_block_tree_js))
319 .route("/cms-admin/static/cms-preview.js", get(serve_cms_preview_js))
320 .route(
321 "/cms-admin/static/menu-builder.js",
322 get(serve_menu_builder_js),
323 )
324 .route(
326 "/cms-admin/static/form_builder.js",
327 get(serve_form_builder_js),
328 )
329 .route(
330 "/cms-admin/static/page_type_builder.js",
331 get(serve_page_type_builder_js),
332 )
333 .route(
335 "/cms-admin/static/page_builder_rules.js",
336 get(serve_page_builder_rules_js),
337 )
338 .route(
343 "/cms-admin/static/vendor/axe-core.min.js",
344 get(serve_axe_core_js),
345 )
346 .route(
350 "/cms-admin/static/cms-axe-preview.js",
351 get(serve_cms_axe_preview_js),
352 )
353 .route(
356 "/cms-admin/static/cms-preview-guard.js",
357 get(serve_cms_preview_guard_js),
358 )
359 .route(
362 "/cms-admin/static/template-editor.js",
363 get(serve_template_editor_js),
364 )
365 .route(
366 "/cms-admin/static/vendor/codemirror.bundle.js",
367 get(serve_codemirror_bundle_js),
368 )
369 .route(
370 "/cms-admin/static/vendor/tiptap.bundle.js",
371 get(serve_tiptap_bundle_js),
372 )
373 .route(
374 "/cms-admin/static/richtext-editor.js",
375 get(serve_richtext_editor_js),
376 )
377 .route(
379 "/cms-admin/static/vendor/THIRD-PARTY-NOTICES.txt",
380 get(serve_third_party_notices),
381 )
382 .with_state(state)
383}
384
385async fn serve_third_party_notices() -> impl axum::response::IntoResponse {
389 (
390 [(
391 axum::http::header::CONTENT_TYPE,
392 axum::http::HeaderValue::from_static("text/plain; charset=utf-8"),
393 )],
394 include_str!("static/vendor/THIRD-PARTY-NOTICES.txt"),
395 )
396}
397
398fn load_or_generate_signing_secret(path: &std::path::Path) -> Vec<u8> {
404 if let Ok(bytes) = std::fs::read(path) {
405 if bytes.len() >= 32 {
406 return bytes;
407 }
408 }
409 let mut buf = [0u8; 32];
416 getrandom::fill(&mut buf).expect("OS CSPRNG unavailable");
417 let buf = buf.to_vec();
418 if let Some(parent) = path.parent() {
419 let _ = std::fs::create_dir_all(parent);
420 }
421 let tmp = path.with_extension("tmp");
422 if std::fs::write(&tmp, &buf).is_ok() && std::fs::rename(&tmp, path).is_ok() {
423 tracing::info!(
424 path = %path.display(),
425 "generated new rustango-cms signing secret; password-reset \
426 links signed with this key. Persisted to disk so links \
427 survive restarts."
428 );
429 } else {
430 tracing::warn!(
431 "could not persist rustango-cms signing secret — \
432 password-reset links will become invalid on every restart"
433 );
434 }
435 buf
436}
437
438pub fn with_login_required(router: Router, login_url: impl Into<String> + 'static) -> Router {
467 use axum::middleware::{from_fn, Next};
468 let login_url: Arc<str> = Arc::from(login_url.into());
469 router.layer(from_fn(
470 move |req: axum::http::Request<axum::body::Body>, next: Next| {
471 let login_url = login_url.clone();
472 async move {
473 use axum::extract::FromRequestParts as _;
474 let (mut parts, body) = req.into_parts();
475 let user = rustango::extractors::SessionUser::from_request_parts(&mut parts, &())
476 .await
477 .unwrap_or(rustango::extractors::SessionUser(None));
478 if let Some(user) = user.0 {
479 let allowed = user.is_superuser
486 || parts.uri.path().starts_with("/cms-admin/static/")
487 || matches!(
488 check_codename(&mut parts, "cms_admin.access").await,
489 AccessResult::Allowed
490 );
491 if !allowed {
492 use axum::response::IntoResponse as _;
493 return axum::response::Redirect::to("/cms-admin/no-access").into_response();
494 }
495 let req = axum::http::Request::from_parts(parts, body);
496 return next.run(req).await;
497 }
498 let original = parts
502 .uri
503 .path_and_query()
504 .map(|p| p.as_str().to_owned())
505 .unwrap_or_else(|| "/".to_owned());
506 rustango::auth_decorators::redirect_to_login(&login_url, "next", &original)
507 }
508 },
509 ))
510}
511
512pub fn with_cms_admin_access(router: Router, no_access_url: impl Into<String>) -> Router {
527 with_codename_gate(router, "cms_admin.access", no_access_url)
528}
529
530pub fn with_codename_gate(
537 router: Router,
538 codename: &'static str,
539 no_access_url: impl Into<String>,
540) -> Router {
541 use axum::middleware::{from_fn, Next};
542 use axum::response::{IntoResponse, Redirect};
543 let no_access_url: Arc<str> = Arc::from(no_access_url.into());
544 router.layer(from_fn(
545 move |req: axum::http::Request<axum::body::Body>, next: Next| {
546 let no_access_url = no_access_url.clone();
547 async move {
548 let path = req.uri().path();
549 if path == &*no_access_url || path.starts_with("/cms-admin/static/") {
550 return next.run(req).await;
551 }
552 let (mut parts, body) = req.into_parts();
553 let outcome = check_codename(&mut parts, codename).await;
554 let req = axum::http::Request::from_parts(parts, body);
555 match outcome {
556 AccessResult::Allowed | AccessResult::DeniedNoUser => next.run(req).await,
557 AccessResult::Denied => Redirect::to(&no_access_url).into_response(),
558 }
559 }
560 },
561 ))
562}
563
564enum AccessResult {
565 Allowed,
566 Denied,
567 DeniedNoUser,
570}
571
572pub(crate) async fn codename_gate(
585 tenant: &rustango::extractors::Tenant,
586 user: Option<&rustango::tenancy::auth::User>,
587 codename: &str,
588) -> Option<axum::response::Response> {
589 use axum::response::{IntoResponse, Redirect};
590 let Some(user) = user else {
591 return Some(Redirect::to("/login").into_response());
592 };
593 if user.is_superuser {
594 return None;
595 }
596 let uid = user.id.get().copied().unwrap_or_default();
597 let codes = crate::permissions::user_codenames(tenant.pool(), uid)
598 .await
599 .unwrap_or_default();
600 if codes.contains(codename) {
601 None
602 } else {
603 Some(Redirect::to("/cms-admin/no-access").into_response())
604 }
605}
606
607async fn check_codename(parts: &mut axum::http::request::Parts, codename: &str) -> AccessResult {
608 let (user, pool) = match request_user_and_pool(parts).await {
609 Ok(Some(found)) => found,
610 Ok(None) => return AccessResult::DeniedNoUser,
611 Err(()) => return AccessResult::Denied,
612 };
613 if user.is_superuser {
614 return AccessResult::Allowed;
615 }
616 let uid = user.id.get().copied().unwrap_or_default();
617 let codenames = crate::permissions::user_codenames(&pool, uid)
618 .await
619 .unwrap_or_default();
620 if codenames.contains(codename) {
621 AccessResult::Allowed
622 } else {
623 AccessResult::Denied
624 }
625}
626
627pub(crate) async fn request_user_and_pool(
632 parts: &mut axum::http::request::Parts,
633) -> Result<Option<(rustango::tenancy::auth::User, rustango::sql::Pool)>, ()> {
634 use axum::extract::FromRequestParts as _;
635 use rustango::tenancy::OrgResolver as _;
636 use std::sync::Arc;
637
638 let Some(ctx) = parts
639 .extensions
640 .get::<Arc<rustango::extractors::TenantContext>>()
641 .cloned()
642 else {
643 return Ok(None);
644 };
645 let Ok(rustango::extractors::SessionUser(Some(user))) =
648 rustango::extractors::SessionUser::from_request_parts(parts, &()).await
649 else {
650 return Ok(None);
651 };
652 let Ok(Some(org)) = ctx.resolver.resolve(parts, &ctx.pools.registry_pool()).await else {
653 return Ok(None);
654 };
655 let pool = ctx.pools.scoped_pool_dyn(&org).await.map_err(|_| ())?;
656 Ok(Some((user, pool)))
657}
658
659fn router_with_state(state: AdminState) -> Router {
660 Router::new()
661 .route("/cms-admin", get(redirect_root))
663 .route("/cms-admin/", get(redirect_root))
664 .route("/cms-admin/pages", get(handlers::page_list))
665 .route(
666 "/cms-admin/pages/new",
667 get(handlers::page_new_form).post(handlers::page_new_submit),
668 )
669 .route(
670 "/cms-admin/pages/{id}/edit",
671 get(handlers::page_edit_form).post(handlers::page_edit_submit),
672 )
673 .route(
674 "/cms-admin/pages/{id}/translate",
675 post(handlers::page_translate_submit),
676 )
677 .route(
678 "/cms-admin/pages/{id}/delete",
679 post(handlers::page_delete_submit),
680 )
681 .route(
682 "/cms-admin/pages/{id}/preview",
683 get(handlers::page_preview).post(handlers::page_preview_draft),
684 )
685 .route(
687 "/cms-admin/pages/{id}/preview-token",
688 get(handlers::page_preview_token),
689 )
690 .route(
692 "/cms-admin/pages/{id}/revert/{rev_id}",
693 post(handlers::page_revert_submit),
694 )
695 .route(
697 "/cms-admin/pages/{id}/history/diff",
698 get(handlers::history_diff),
699 )
700 .route("/cms-admin/pages/{id}/log.csv", get(handlers::page_log_csv))
702 .route(
705 "/cms-admin/pages/{id}/permissions",
706 post(handlers::page_permissions_submit),
707 )
708 .route(
710 "/cms-admin/pages/{id}/move",
711 post(handlers::page_move_submit),
712 )
713 .route(
715 "/cms-admin/pages/{id}/clone",
716 post(handlers::page_clone_submit),
717 )
718 .route(
720 "/cms-admin/pages/{id}/alias",
721 post(handlers::page_alias_submit),
722 )
723 .route(
725 "/cms-admin/pages/{id}/privacy",
726 post(handlers::page_privacy_submit),
727 )
728 .route("/cms-admin/pages/bulk", post(handlers::page_bulk_submit))
732 .route(
734 "/cms-admin/pages/{id}/unlock",
735 post(handlers::page_unlock_submit),
736 )
737 .route(
738 "/cms-admin/pages/{id}/lock-release",
739 post(handlers::page_lock_release),
740 )
741 .route(
742 "/cms-admin/pages/{id}/lock-heartbeat",
743 post(handlers::page_lock_heartbeat),
744 )
745 .route(
747 "/cms-admin/pages/{id}/autosave",
748 post(handlers::page_autosave_submit),
749 )
750 .route(
752 "/cms-admin/pages/{id}/sessions",
753 get(handlers::page_sessions_json),
754 )
755 .route(
757 "/cms-admin/pages/{id}/subscribe",
758 post(handlers::page_subscribe_submit),
759 )
760 .route(
761 "/cms-admin/pages/{id}/unsubscribe",
762 post(handlers::page_unsubscribe_submit),
763 )
764 .route(
766 "/cms-admin/pages/{id}/comments/new",
767 post(handlers::comment_new_submit),
768 )
769 .route(
770 "/cms-admin/pages/{id}/comments/{comment_id}/reply",
771 post(handlers::comment_reply_submit),
772 )
773 .route(
774 "/cms-admin/pages/{id}/comments/{comment_id}/resolve",
775 post(handlers::comment_resolve_submit),
776 )
777 .route(
778 "/cms-admin/pages/{id}/comments/{comment_id}/reopen",
779 post(handlers::comment_reopen_submit),
780 )
781 .route(
783 "/cms-admin/pages/{id}/workflow/submit",
784 post(handlers::page_workflow_submit),
785 )
786 .route(
787 "/cms-admin/pages/{id}/workflow/approve",
788 post(handlers::page_workflow_approve),
789 )
790 .route(
791 "/cms-admin/pages/{id}/workflow/reject",
792 post(handlers::page_workflow_reject),
793 )
794 .route(
795 "/cms-admin/pages/{id}/workflow/cancel",
796 post(handlers::page_workflow_cancel),
797 )
798 .route("/cms-admin/library", get(handlers::library_list))
800 .route("/cms-admin/forms", get(handlers::forms_list))
804 .route("/cms-admin/set-language", post(handlers::admin_set_language))
806 .route(
809 "/cms-admin/forms/{id}/build",
810 get(handlers::form_build_form).post(handlers::form_build_submit),
811 )
812 .route(
815 "/cms-admin/forms/{id}/preview",
816 get(handlers::form_preview).post(handlers::form_preview_draft),
817 )
818 .route(
820 "/cms-admin/forms/{id}/publish",
821 post(handlers::form_publish_submit),
822 )
823 .route(
825 "/cms-admin/forms/{id}/submissions",
826 get(handlers::form_submissions_list),
827 )
828 .route(
829 "/cms-admin/forms/{id}/submissions/export.csv",
830 get(handlers::form_submissions_csv),
831 )
832 .route(
834 "/cms-admin/forms/{id}/submissions/file/{key}",
835 get(handlers::form_submission_file),
836 )
837 .route(
838 "/cms-admin/library/new",
839 get(handlers::snippet_new_form).post(handlers::snippet_create_submit),
840 )
841 .route(
842 "/cms-admin/library/{id}/edit",
843 get(handlers::snippet_edit_form).post(handlers::snippet_edit_submit),
844 )
845 .route(
847 "/cms-admin/library/{id}/translate",
848 post(handlers::snippet_translate_submit),
849 )
850 .route(
854 "/cms-admin/library/{type_name}/bulk",
855 post(handlers::library_bulk_submit),
856 )
857 .route(
858 "/cms-admin/library/{id}/delete",
859 post(handlers::snippet_delete_submit),
860 )
861 .route(
863 "/cms-admin/library/{id}/revert/{seq}",
864 post(handlers::snippet_revert_submit),
865 )
866 .route(
868 "/cms-admin/library/{type_name}/import",
869 get(handlers::snippet_import_form).post(handlers::snippet_import_submit),
870 )
871 .route("/cms-admin/media", get(handlers::media_list))
873 .route(
875 "/cms-admin/media/{id}/edit",
876 get(handlers::media_edit_form).post(handlers::media_edit_submit),
877 )
878 .route(
880 "/cms-admin/media/{id}/crop",
881 post(handlers::media_crop_submit),
882 )
883 .route(
885 "/cms-admin/media/{id}/replace",
886 post(handlers::media_replace_submit),
887 )
888 .route(
890 "/cms-admin/media/collections",
891 get(handlers::collections_list),
892 )
893 .route(
894 "/cms-admin/media/collections/new",
895 post(handlers::collections_create),
896 )
897 .route(
898 "/cms-admin/media/collections/{id}/edit",
899 post(handlers::collections_edit),
900 )
901 .route(
902 "/cms-admin/media/collections/{id}/delete",
903 post(handlers::collections_delete),
904 )
905 .route(
906 "/cms-admin/media/bulk-move-collection",
907 post(handlers::media_bulk_move_collection),
908 )
909 .route("/cms-admin/taxonomies", get(handlers::taxonomies_index))
912 .route("/cms-admin/taxonomies/{slug}", get(handlers::category_tree))
913 .route(
914 "/cms-admin/taxonomies/{slug}/categories/new",
915 get(handlers::category_new_form).post(handlers::category_create),
916 )
917 .route(
918 "/cms-admin/taxonomies/{slug}/categories/{id}/edit",
919 get(handlers::category_edit_form).post(handlers::category_update),
920 )
921 .route(
922 "/cms-admin/taxonomies/{slug}/categories/{id}/delete",
923 post(handlers::category_delete),
924 )
925 .route(
927 "/cms-admin/taxonomies/{slug}/categories/{id}/translate",
928 post(handlers::category_translate_submit),
929 )
930 .route(
932 "/cms-admin/media/collections/{id}/permissions",
933 get(handlers::collection_permissions_form)
934 .post(handlers::collection_permissions_submit),
935 )
936 .route(
938 "/cms-admin/media/collections/{id}/privacy",
939 post(handlers::collection_privacy_submit),
940 )
941 .route(
944 "/cms-admin/media/unused",
945 get(handlers::media_unused_report),
946 )
947 .route(
948 "/cms-admin/media/unused/delete",
949 post(handlers::media_unused_bulk_delete),
950 )
951 .route(
952 "/cms-admin/media/upload",
953 get(handlers::media_upload_form).post(handlers::media_upload_submit),
954 )
955 .route(
959 "/cms-admin/media/upload-staged",
960 post(handlers::media_upload_staged)
961 .route_layer(axum::extract::DefaultBodyLimit::max(50 * 1024 * 1024)),
962 )
963 .route(
964 "/cms-admin/media/upload-staged/{id}/cancel",
965 post(handlers::media_upload_staged_cancel),
966 )
967 .route(
969 "/cms-admin/media/upload-staged/commit",
970 post(handlers::media_upload_staged_commit),
971 )
972 .route(
973 "/cms-admin/media/{id}/delete",
974 post(handlers::media_delete_submit),
975 )
976 .route("/cms-admin/documents", get(handlers::documents_list))
977 .route("/cms-admin/model/{slug}", get(handlers::model_admin_list))
979 .route("/cms-admin/report/{slug}", get(handlers::report_view))
982 .route(
986 "/cms-admin/__chooser/{slug}",
987 get(handlers::chooser_search_json),
988 )
989 .route(
993 "/cms-admin/__media-picker",
994 get(handlers::media_picker_json),
995 )
996 .route("/cms-admin/sso-providers", get(handlers::sso_provider_list))
998 .route(
999 "/cms-admin/sso-providers/new",
1000 get(handlers::sso_provider_new_form).post(handlers::sso_provider_new_submit),
1001 )
1002 .route(
1003 "/cms-admin/sso-providers/{id}/edit",
1004 get(handlers::sso_provider_edit_form).post(handlers::sso_provider_edit_submit),
1005 )
1006 .route(
1007 "/cms-admin/sso-providers/{id}/delete",
1008 post(handlers::sso_provider_delete_submit),
1009 )
1010 .route("/cms-admin/locales", get(handlers::locale_list))
1012 .route(
1013 "/cms-admin/locales/new",
1014 get(handlers::locale_new_form).post(handlers::locale_new_submit),
1015 )
1016 .route(
1017 "/cms-admin/locales/{id}/edit",
1018 get(handlers::locale_edit_form).post(handlers::locale_edit_submit),
1019 )
1020 .route(
1021 "/cms-admin/locales/{id}/delete",
1022 post(handlers::locale_delete_submit),
1023 )
1024 .route("/cms-admin/search", get(handlers::admin_search))
1028 .route(
1031 "/cms-admin/site-settings",
1032 get(handlers::site_settings_list),
1033 )
1034 .route(
1035 "/cms-admin/site-settings/{scope}/edit",
1036 get(handlers::site_setting_edit_form).post(handlers::site_setting_edit_submit),
1037 )
1038 .route(
1039 "/cms-admin/site-settings/{scope}/delete",
1040 post(handlers::site_setting_delete_submit),
1041 )
1042 .route(
1044 "/cms-admin/site-settings/{scope}/translate",
1045 post(handlers::site_setting_translate_submit),
1046 )
1047 .route("/cms-admin/templates", get(template_editor::list))
1050 .route(
1051 "/cms-admin/templates/edit",
1052 get(template_editor::edit_form).post(template_editor::save),
1053 )
1054 .route("/cms-admin/templates/new", post(template_editor::create))
1055 .route(
1056 "/cms-admin/templates/validate",
1057 post(template_editor::validate),
1058 )
1059 .route("/cms-admin/templates/delete", post(template_editor::delete))
1060 .route(
1063 "/cms-admin/page-types/{id}/template",
1064 get(template_editor::assign_form).post(template_editor::assign_save),
1065 )
1066 .route("/cms-admin/analytics", get(handlers::analytics_dashboard))
1067 .route(
1068 "/cms-admin/reports/aging",
1069 get(handlers::aging_pages_report),
1070 )
1071 .route(
1072 "/cms-admin/reports/aging.csv",
1073 get(handlers::aging_pages_csv),
1074 )
1075 .route(
1076 "/cms-admin/reports/locked-pages",
1077 get(handlers::locked_pages_report),
1078 )
1079 .route(
1080 "/cms-admin/reports/locked-pages.csv",
1081 get(handlers::locked_pages_csv),
1082 )
1083 .route(
1084 "/cms-admin/reports/workflows",
1085 get(handlers::workflows_report),
1086 )
1087 .route(
1088 "/cms-admin/reports/workflows.csv",
1089 get(handlers::workflows_report_csv),
1090 )
1091 .route(
1093 "/cms-admin/reports/revisions",
1094 get(handlers::revisions_report),
1095 )
1096 .route(
1097 "/cms-admin/reports/revisions/prune",
1098 post(handlers::revisions_report_prune),
1099 )
1100 .route(
1102 "/cms-admin/reports/scheduled",
1103 get(handlers::scheduled_report),
1104 )
1105 .route(
1106 "/cms-admin/reports/scheduled.csv",
1107 get(handlers::scheduled_report_csv),
1108 )
1109 .route(
1111 "/cms-admin/reports/search",
1112 get(handlers::search_promotions_report),
1113 )
1114 .route(
1115 "/cms-admin/reports/search/{id}/edit",
1116 get(handlers::search_promotion_edit_form).post(handlers::search_promotion_edit_submit),
1117 )
1118 .route("/cms-admin/workflows", get(handlers::workflows_list))
1119 .route(
1120 "/cms-admin/workflows/new",
1121 get(handlers::workflow_new_form).post(handlers::workflow_new_submit),
1122 )
1123 .route(
1124 "/cms-admin/workflows/{id}/edit",
1125 get(handlers::workflow_edit_form).post(handlers::workflow_edit_submit),
1126 )
1127 .route(
1128 "/cms-admin/workflows/{id}/delete",
1129 post(handlers::workflow_delete_submit),
1130 )
1131 .route(
1132 "/cms-admin/workflows/{id}/tasks/add",
1133 post(handlers::workflow_task_add),
1134 )
1135 .route(
1136 "/cms-admin/workflows/{id}/tasks/{task_id}/delete",
1137 post(handlers::workflow_task_delete),
1138 )
1139 .route("/cms-admin/notifications", get(notifications::list))
1144 .route("/cms-admin/notifications/new", post(notifications::create))
1145 .route(
1146 "/cms-admin/notifications/{id}/toggle",
1147 post(notifications::toggle),
1148 )
1149 .route(
1150 "/cms-admin/notifications/{id}/delete",
1151 post(notifications::delete),
1152 )
1153 .route(
1154 "/cms-admin/notifications/deliveries/{id}/retry",
1155 post(notifications::retry_delivery),
1156 )
1157 .route("/cms-admin/sites", get(sites::list))
1162 .route("/cms-admin/sites/new", post(sites::add))
1163 .route("/cms-admin/sites/root", post(sites::set_root))
1164 .route("/cms-admin/sites/toggle", post(sites::toggle))
1165 .route("/cms-admin/sites/delete", post(sites::remove))
1166 .route("/cms-admin/redirects", get(handlers::redirect_list))
1167 .route(
1168 "/cms-admin/redirects/new",
1169 get(handlers::redirect_new_form).post(handlers::redirect_new_submit),
1170 )
1171 .route(
1172 "/cms-admin/redirects/{id}/edit",
1173 get(handlers::redirect_edit_form).post(handlers::redirect_edit_submit),
1174 )
1175 .route(
1176 "/cms-admin/redirects/{id}/delete",
1177 post(handlers::redirect_delete_submit),
1178 )
1179 .route(
1181 "/cms-admin/redirects/{id}/enable",
1182 post(handlers::redirect_enable_submit),
1183 )
1184 .route(
1186 "/cms-admin/redirects/import",
1187 get(handlers::redirect_import_form).post(handlers::redirect_import_submit),
1188 )
1189 .route(
1191 "/cms-admin/redirects/export.csv",
1192 get(handlers::redirect_export_csv),
1193 )
1194 .route("/cms-admin/users", get(handlers::users_list))
1196 .route("/cms-admin/users/bulk", post(handlers::users_bulk_submit))
1198 .route(
1199 "/cms-admin/users/new",
1200 get(handlers::users_new_form).post(handlers::users_create_submit),
1201 )
1202 .route(
1203 "/cms-admin/users/{id}/edit",
1204 get(handlers::users_edit_form).post(handlers::users_edit_submit),
1205 )
1206 .route(
1207 "/cms-admin/users/{id}/deactivate",
1208 post(handlers::users_deactivate_submit),
1209 )
1210 .route("/cms-admin/roles", get(handlers::roles_list))
1211 .route(
1213 "/cms-admin/permissions",
1214 get(handlers::permissions_overview),
1215 )
1216 .route(
1217 "/cms-admin/roles/new",
1218 get(handlers::roles_new_form).post(handlers::roles_create_submit),
1219 )
1220 .route(
1221 "/cms-admin/roles/{id}/edit",
1222 get(handlers::roles_edit_form).post(handlers::roles_edit_submit),
1223 )
1224 .route(
1225 "/cms-admin/roles/{id}/delete",
1226 post(handlers::roles_delete_submit),
1227 )
1228 .route("/cms-admin/navigation", get(handlers::navigation_list))
1230 .route(
1231 "/cms-admin/navigation/new",
1232 post(handlers::navigation_create_submit),
1233 )
1234 .route(
1235 "/cms-admin/navigation/{id}/delete",
1236 post(handlers::navigation_delete_submit),
1237 )
1238 .route(
1239 "/cms-admin/navigation/{id}/clone",
1240 post(handlers::navigation_clone_submit),
1241 )
1242 .route(
1243 "/cms-admin/navigation/{id}/save-tree",
1244 post(handlers::navigation_save_tree_submit),
1245 )
1246 .route(
1251 "/cms-admin/navigation/{id}/seed-from-pages",
1252 post(handlers::navigation_seed_from_pages_submit),
1253 )
1254 .route(
1255 "/cms-admin/navigation/{id}/edit",
1256 get(handlers::navigation_edit_form),
1257 )
1258 .route(
1259 "/cms-admin/navigation/{id}/translate",
1260 post(handlers::navigation_translate_submit),
1261 )
1262 .route(
1263 "/cms-admin/navigation/{id}/items",
1264 post(handlers::navigation_item_create),
1265 )
1266 .route(
1267 "/cms-admin/navigation/{menu_id}/items/{id}/delete",
1268 post(handlers::navigation_item_delete),
1269 )
1270 .route("/cms-admin/history", get(handlers::history_page))
1272 .route("/cms-admin/page-types", get(handlers::page_types_dashboard))
1274 .route(
1276 "/cms-admin/page-types/new",
1277 get(handlers::page_type_new_form).post(handlers::page_type_create),
1278 )
1279 .route(
1280 "/cms-admin/page-types/{id}/edit",
1281 get(handlers::page_type_edit_form).post(handlers::page_type_update),
1282 )
1283 .route(
1284 "/cms-admin/page-types/{id}/delete",
1285 post(handlers::page_type_delete),
1286 )
1287 .route(
1289 "/cms-admin/page-types/{id}/build",
1290 get(handlers::page_type_build_form).post(handlers::page_type_build_submit),
1291 )
1292 .route(
1293 "/cms-admin/page-types/{id}/build/publish",
1294 post(handlers::page_type_publish_submit),
1295 )
1296 .route(
1298 "/cms-admin/page-types/{id}/translate",
1299 get(handlers::page_type_translate_form).post(handlers::page_type_translate_submit),
1300 )
1301 .route("/cms-admin/components", get(handlers::components_index))
1303 .route(
1304 "/cms-admin/components/new",
1305 get(handlers::component_new_form).post(handlers::component_create),
1306 )
1307 .route(
1308 "/cms-admin/components/{id}/edit",
1309 get(handlers::component_edit_form).post(handlers::component_update),
1310 )
1311 .route(
1312 "/cms-admin/components/{id}/delete",
1313 post(handlers::component_delete),
1314 )
1315 .route("/cms-admin/settings", get(handlers::settings_page))
1317 .route(
1319 "/cms-admin/settings/branding",
1320 post(handlers::settings_branding_submit),
1321 )
1322 .route(
1327 "/cms-admin/settings/theme",
1328 post(handlers::settings_theme_switch),
1329 )
1330 .route(
1335 "/cms-admin/__richtext-preview",
1336 post(handlers::richtext_preview),
1337 )
1338 .route("/cms-admin/me", get(handlers::account_preferences))
1341 .route(
1343 "/cms-admin/__page-chooser",
1344 get(handlers::page_chooser_json),
1345 )
1346 .route(
1348 "/cms-admin/__snippet-chooser",
1349 get(handlers::snippet_chooser_json),
1350 )
1351 .route(
1352 "/cms-admin/__document-chooser",
1353 get(handlers::document_chooser_json),
1354 )
1355 .route(
1358 "/cms-admin/me/notifications",
1359 post(handlers::account_notifications_submit),
1360 )
1361 .route(
1363 "/cms-admin/me/profile",
1364 post(handlers::account_profile_submit),
1365 )
1366 .route(
1368 "/cms-admin/me/language",
1369 post(handlers::account_language_submit),
1370 )
1371 .route("/cms-admin/me/email", post(handlers::account_email_submit))
1373 .route(
1374 "/cms-admin/me/email/confirm",
1375 get(handlers::account_email_confirm),
1376 )
1377 .route(
1378 "/cms-admin/me/password",
1379 post(handlers::account_password_submit),
1380 )
1381 .route(
1384 "/cms-admin/me/mcp-keys",
1385 post(handlers::account_mcp_key_create),
1386 )
1387 .route(
1388 "/cms-admin/me/mcp-keys/{id}/revoke",
1389 post(handlers::account_mcp_key_revoke),
1390 )
1391 .route(
1395 "/cms-admin/users/{id}/mcp-keys",
1396 post(handlers::users_mcp_key_create),
1397 )
1398 .route(
1399 "/cms-admin/users/{id}/mcp-keys/{key_id}/revoke",
1400 post(handlers::users_mcp_key_revoke),
1401 )
1402 .route(
1406 "/__cms-avatar/{user_id}",
1407 get(handlers::account_avatar_serve),
1408 )
1409 .route("/cms-admin/styleguide", get(handlers::styleguide))
1411 .route("/cms-admin/dashboard", get(handlers::dashboard))
1413 .route(
1415 "/cms-admin/dismissibles/{key}",
1416 post(handlers::dismissible_submit),
1417 )
1418 .route("/cms-admin/logout", post(handlers::cms_logout_submit))
1426 .route("/cms-admin/x/{slug}", get(handlers::admin_page_dispatch))
1431 .route_layer(axum::middleware::from_fn(route_perms::gate))
1434 .route_layer(axum::middleware::from_fn(crate::seed::lazy_seed_layer))
1437 .with_state(state)
1438}
1439
1440async fn redirect_root() -> axum::response::Redirect {
1441 axum::response::Redirect::permanent("/cms-admin/dashboard")
1443}
1444
1445fn immutable_asset<B: axum::response::IntoResponse>(
1450 content_type: &'static str,
1451 body: B,
1452) -> axum::response::Response {
1453 use axum::response::IntoResponse as _;
1454 (
1455 [
1456 (
1457 axum::http::header::CONTENT_TYPE,
1458 axum::http::HeaderValue::from_static(content_type),
1459 ),
1460 (
1461 axum::http::header::CACHE_CONTROL,
1462 axum::http::HeaderValue::from_static("public, max-age=31536000, immutable"),
1463 ),
1464 ],
1465 body,
1466 )
1467 .into_response()
1468}
1469
1470async fn serve_stream_editor_js() -> impl axum::response::IntoResponse {
1472 immutable_asset("text/javascript; charset=utf-8", include_str!("static/stream_editor.js"))
1473}
1474
1475async fn serve_cms_preview_js() -> impl axum::response::IntoResponse {
1479 immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-preview.js"))
1480}
1481
1482async fn serve_block_tree_js() -> impl axum::response::IntoResponse {
1484 immutable_asset("text/javascript; charset=utf-8", include_str!("static/block_tree.js"))
1485}
1486
1487async fn serve_cms_ux_js() -> impl axum::response::IntoResponse {
1493 immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-ux.js"))
1494}
1495
1496async fn serve_menu_builder_js() -> impl axum::response::IntoResponse {
1500 immutable_asset("text/javascript; charset=utf-8", include_str!("static/menu-builder.js"))
1501}
1502
1503async fn serve_form_builder_js() -> impl axum::response::IntoResponse {
1506 immutable_asset("text/javascript; charset=utf-8", include_str!("static/form_builder.js"))
1507}
1508
1509async fn serve_page_type_builder_js() -> impl axum::response::IntoResponse {
1510 immutable_asset("text/javascript; charset=utf-8", include_str!("static/page_type_builder.js"))
1511}
1512
1513async fn serve_page_builder_rules_js() -> impl axum::response::IntoResponse {
1514 immutable_asset("text/javascript; charset=utf-8", include_str!("static/page_builder_rules.js"))
1515}
1516
1517async fn serve_axe_core_js() -> impl axum::response::IntoResponse {
1522 immutable_asset("text/javascript; charset=utf-8", include_str!("static/vendor/axe-core.min.js"))
1523}
1524
1525async fn serve_cms_axe_preview_js() -> impl axum::response::IntoResponse {
1531 immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-axe-preview.js"))
1532}
1533
1534async fn serve_cms_preview_guard_js() -> impl axum::response::IntoResponse {
1539 immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-preview-guard.js"))
1540}
1541
1542const ADMIN_FONT_FILES: &[(&str, &[u8])] = &[
1555 (
1556 "icons-00.woff2",
1557 include_bytes!("static/vendor/fonts/icons-00.woff2"),
1558 ),
1559 (
1560 "text-00.woff2",
1561 include_bytes!("static/vendor/fonts/text-00.woff2"),
1562 ),
1563 (
1564 "text-02.woff2",
1565 include_bytes!("static/vendor/fonts/text-02.woff2"),
1566 ),
1567 (
1568 "text-03.woff2",
1569 include_bytes!("static/vendor/fonts/text-03.woff2"),
1570 ),
1571 (
1572 "text-16.woff2",
1573 include_bytes!("static/vendor/fonts/text-16.woff2"),
1574 ),
1575 (
1576 "text-17.woff2",
1577 include_bytes!("static/vendor/fonts/text-17.woff2"),
1578 ),
1579 (
1580 "text-21.woff2",
1581 include_bytes!("static/vendor/fonts/text-21.woff2"),
1582 ),
1583 (
1584 "text-22.woff2",
1585 include_bytes!("static/vendor/fonts/text-22.woff2"),
1586 ),
1587];
1588
1589async fn serve_admin_fonts_css() -> impl axum::response::IntoResponse {
1592 immutable_asset("text/css; charset=utf-8", include_str!("static/vendor/fonts/fonts.css"))
1593}
1594
1595async fn serve_admin_font_file(axum::extract::Path(file): axum::extract::Path<String>) -> Response {
1598 match ADMIN_FONT_FILES.iter().find(|(name, _)| *name == file) {
1599 Some((_, bytes)) => immutable_asset("font/woff2", *bytes)
1600 .into_response(),
1601 None => (axum::http::StatusCode::NOT_FOUND, "unknown font").into_response(),
1602 }
1603}
1604
1605const ADMIN_BRAND_FILES: &[(&str, &str, &[u8])] = &[
1609 ("logo-light.png", "image/png", include_bytes!("static/brand/logo-light.png")),
1610 ("logo-dark.png", "image/png", include_bytes!("static/brand/logo-dark.png")),
1611 ("icon-light.png", "image/png", include_bytes!("static/brand/icon-light.png")),
1612 ("icon-dark.png", "image/png", include_bytes!("static/brand/icon-dark.png")),
1613 ("favicon.ico", "image/x-icon", include_bytes!("static/brand/favicon.ico")),
1614 ("apple-touch-icon.png", "image/png", include_bytes!("static/brand/apple-touch-icon.png")),
1615];
1616
1617async fn serve_admin_brand_file(axum::extract::Path(file): axum::extract::Path<String>) -> Response {
1618 match ADMIN_BRAND_FILES.iter().find(|(name, _, _)| *name == file) {
1619 Some((_, content_type, bytes)) => immutable_asset(content_type, *bytes).into_response(),
1620 None => (axum::http::StatusCode::NOT_FOUND, "unknown brand file").into_response(),
1621 }
1622}
1623
1624async fn serve_tiptap_bundle_js() -> impl axum::response::IntoResponse {
1629 immutable_asset("text/javascript; charset=utf-8", include_str!("static/vendor/tiptap.bundle.js"))
1630}
1631
1632async fn serve_template_editor_js() -> impl axum::response::IntoResponse {
1636 immutable_asset("text/javascript; charset=utf-8", include_str!("static/template-editor.js"))
1637}
1638
1639async fn serve_codemirror_bundle_js() -> impl axum::response::IntoResponse {
1643 immutable_asset("text/javascript; charset=utf-8", include_str!("static/vendor/codemirror.bundle.js"))
1644}
1645
1646async fn serve_richtext_editor_js() -> impl axum::response::IntoResponse {
1651 immutable_asset("text/javascript; charset=utf-8", include_str!("static/richtext-editor.js"))
1652}
1653
1654const BUNDLED_CMS_CSS: &str = include_str!("static/cms.css");
1658
1659async fn serve_cms_css() -> Response {
1667 let override_path = std::path::Path::new("static/cms_admin/cms.css");
1668 if override_path.exists() {
1669 match std::fs::read_to_string(override_path) {
1670 Ok(source) => {
1671 return (
1672 [
1673 (
1674 axum::http::header::CONTENT_TYPE,
1675 axum::http::HeaderValue::from_static("text/css; charset=utf-8"),
1676 ),
1677 (
1681 axum::http::header::CACHE_CONTROL,
1682 axum::http::HeaderValue::from_static(
1683 "public, max-age=31536000, immutable",
1684 ),
1685 ),
1686 ],
1687 source,
1688 )
1689 .into_response();
1690 }
1691 Err(err) => {
1692 tracing::warn!(
1693 target: "rustango_cms::admin",
1694 error = %err,
1695 path = %override_path.display(),
1696 "failed to read cms.css override; falling back to bundled stylesheet",
1697 );
1698 }
1699 }
1700 }
1701 immutable_asset("text/css; charset=utf-8", BUNDLED_CMS_CSS)
1702 .into_response()
1703}
1704
1705fn cms_asset_version() -> String {
1719 static BUNDLED: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
1720 let bundled = *BUNDLED.get_or_init(|| {
1721 let mut h: u64 = 0xcbf29ce4_84222325;
1724 let mut feed_bytes = |bytes: &[u8]| {
1725 for &b in bytes {
1726 h ^= u64::from(b);
1727 h = h.wrapping_mul(0x0000_0100_0000_01b3);
1728 }
1729 };
1730 for (_, _, bytes) in ADMIN_BRAND_FILES {
1732 feed_bytes(bytes);
1733 }
1734 let mut feed = |s: &str| feed_bytes(s.as_bytes());
1735 feed(BUNDLED_CMS_CSS);
1736 feed(include_str!("static/cms-ux.js"));
1737 feed(include_str!("static/stream_editor.js"));
1738 feed(include_str!("static/richtext-editor.js"));
1739 feed(include_str!("static/block_tree.js"));
1743 feed(include_str!("static/page_type_builder.js"));
1744 feed(include_str!("static/form_builder.js"));
1745 feed(include_str!("static/menu-builder.js"));
1746 feed(include_str!("static/cms-axe-preview.js"));
1747 feed(include_str!("static/cms-preview-guard.js"));
1748 feed(include_str!("static/cms-preview.js"));
1749 feed(include_str!("static/page_builder_rules.js"));
1750 h
1751 });
1752 if let Ok(meta) = std::fs::metadata("static/cms_admin/cms.css") {
1753 let mtime = meta
1754 .modified()
1755 .ok()
1756 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1757 .map_or(0, |d| d.as_secs());
1758 return format!("{bundled:x}.{mtime:x}.{:x}", meta.len());
1759 }
1760 format!("{bundled:x}")
1761}
1762
1763struct CmsAssetVersionFn;
1765
1766impl tera::Function for CmsAssetVersionFn {
1767 fn call(
1768 &self,
1769 _args: &std::collections::HashMap<String, tera::Value>,
1770 ) -> tera::Result<tera::Value> {
1771 Ok(tera::Value::String(cms_asset_version()))
1772 }
1773}
1774
1775struct JsonScriptFilter;
1784
1785impl tera::Filter for JsonScriptFilter {
1786 fn filter(
1787 &self,
1788 value: &tera::Value,
1789 _args: &std::collections::HashMap<String, tera::Value>,
1790 ) -> tera::Result<tera::Value> {
1791 Ok(tera::Value::String(json_script(value)))
1792 }
1793
1794 fn is_safe(&self) -> bool {
1795 true
1796 }
1797}
1798
1799fn json_script(value: &tera::Value) -> String {
1800 serde_json::to_string(value)
1801 .unwrap_or_else(|_| "null".to_owned())
1802 .replace('<', "\\u003c")
1803 .replace('>', "\\u003e")
1804 .replace('&', "\\u0026")
1805 .replace('\'', "\\u0027")
1806}
1807
1808pub fn register_templates(tera: &mut Tera) -> Result<(), tera::Error> {
1852 crate::urls::register_tera_helpers(tera);
1853 tera.register_function("cms_asset_version", CmsAssetVersionFn);
1856 tera.register_filter("json_script", JsonScriptFilter);
1857 rustango::i18n::tera_tags::register(tera, i18n::cached_translator().clone());
1863 tera.register_function(
1875 "get_env",
1876 |_args: &std::collections::HashMap<String, tera::Value>| -> tera::Result<tera::Value> {
1877 Err(tera::Error::msg(
1878 "get_env is disabled in CMS templates for security reasons",
1879 ))
1880 },
1881 );
1882 tera.add_raw_templates(vec![
1883 (
1884 "rcms_admin/_base.html",
1885 include_str!("templates/_base.html"),
1886 ),
1887 (
1888 "rcms_admin/_auth_layout.html",
1889 include_str!("templates/_auth_layout.html"),
1890 ),
1891 (
1894 "rcms_admin/_brand_icons.html",
1895 include_str!("templates/_brand_icons.html"),
1896 ),
1897 (
1900 "rcms_admin/_list_base.html",
1901 include_str!("templates/_list_base.html"),
1902 ),
1903 (
1910 "rcms_admin/_stream_widget.html",
1911 "{% import \"rcms_admin/_widget.html\" as widget %}{{ widget::render(w=w) }}",
1912 ),
1913 (
1914 "rcms_admin/member_login.html",
1915 include_str!("templates/member_login.html"),
1916 ),
1917 (
1918 "rcms_admin/member_signup.html",
1919 include_str!("templates/member_signup.html"),
1920 ),
1921 (
1922 "rcms_admin/_mcp_keys_card.html",
1923 include_str!("templates/_mcp_keys_card.html"),
1924 ),
1925 (
1926 "rcms_admin/_pagination.html",
1927 include_str!("templates/_pagination.html"),
1928 ),
1929 (
1930 "rcms_admin/_preview_pane.html",
1931 include_str!("templates/_preview_pane.html"),
1932 ),
1933 (
1934 "rcms_admin/notifications.html",
1935 include_str!("templates/notifications.html"),
1936 ),
1937 ("rcms_admin/sites.html", include_str!("templates/sites.html")),
1938 (
1939 "rcms_admin/_widget.html",
1940 include_str!("templates/_widget.html"),
1941 ),
1942 (
1943 "rcms_admin/_widget_group.html",
1944 include_str!("templates/_widget_group.html"),
1945 ),
1946 (
1947 "rcms_admin/_permissions_tab.html",
1948 include_str!("templates/_permissions_tab.html"),
1949 ),
1950 (
1951 "rcms_admin/page_list.html",
1952 include_str!("templates/page_list.html"),
1953 ),
1954 (
1955 "rcms_admin/page_form.html",
1956 include_str!("templates/page_form.html"),
1957 ),
1958 (
1959 "rcms_admin/page_type_picker.html",
1960 include_str!("templates/page_type_picker.html"),
1961 ),
1962 (
1963 "rcms_admin/library_list.html",
1964 include_str!("templates/library_list.html"),
1965 ),
1966 (
1967 "rcms_admin/snippet_form.html",
1968 include_str!("templates/snippet_form.html"),
1969 ),
1970 (
1971 "rcms_admin/form_builder.html",
1972 include_str!("templates/form_builder.html"),
1973 ),
1974 (
1975 "rcms_admin/form_submissions.html",
1976 include_str!("templates/form_submissions.html"),
1977 ),
1978 (
1979 "rcms_admin/forms_list.html",
1980 include_str!("templates/forms_list.html"),
1981 ),
1982 (
1983 "rcms_admin/form_translate.html",
1984 include_str!("templates/form_translate.html"),
1985 ),
1986 (
1987 "rcms_admin/page_type_translate.html",
1988 include_str!("templates/page_type_translate.html"),
1989 ),
1990 (
1991 "rcms_admin/media_list.html",
1992 include_str!("templates/media_list.html"),
1993 ),
1994 (
1995 "rcms_admin/media_upload.html",
1996 include_str!("templates/media_upload.html"),
1997 ),
1998 (
1999 "rcms_admin/model_admin_list.html",
2000 include_str!("templates/model_admin_list.html"),
2001 ),
2002 (
2003 "rcms_admin/report.html",
2004 include_str!("templates/report.html"),
2005 ),
2006 (
2007 "rcms_admin/locale_list.html",
2008 include_str!("templates/locale_list.html"),
2009 ),
2010 (
2011 "rcms_admin/locale_form.html",
2012 include_str!("templates/locale_form.html"),
2013 ),
2014 (
2015 "rcms_admin/sso_provider_list.html",
2016 include_str!("templates/sso_provider_list.html"),
2017 ),
2018 (
2019 "rcms_admin/sso_provider_form.html",
2020 include_str!("templates/sso_provider_form.html"),
2021 ),
2022 (
2023 "rcms_admin/workflow_list.html",
2024 include_str!("templates/workflow_list.html"),
2025 ),
2026 (
2027 "rcms_admin/workflow_form.html",
2028 include_str!("templates/workflow_form.html"),
2029 ),
2030 (
2031 "rcms_admin/history_diff.html",
2032 include_str!("templates/history_diff.html"),
2033 ),
2034 (
2035 "rcms_admin/admin_search.html",
2036 include_str!("templates/admin_search.html"),
2037 ),
2038 (
2039 "rcms_admin/analytics.html",
2040 include_str!("templates/analytics.html"),
2041 ),
2042 (
2043 "rcms_admin/aging_pages.html",
2044 include_str!("templates/aging_pages.html"),
2045 ),
2046 (
2047 "rcms_admin/locked_pages.html",
2048 include_str!("templates/locked_pages.html"),
2049 ),
2050 (
2051 "rcms_admin/workflow_report.html",
2052 include_str!("templates/workflow_report.html"),
2053 ),
2054 (
2055 "rcms_admin/revisions_report.html",
2056 include_str!("templates/revisions_report.html"),
2057 ),
2058 (
2059 "rcms_admin/scheduled_report.html",
2060 include_str!("templates/scheduled_report.html"),
2061 ),
2062 (
2063 "rcms_admin/search_promotions_report.html",
2064 include_str!("templates/search_promotions_report.html"),
2065 ),
2066 (
2067 "rcms_admin/search_promotion_edit.html",
2068 include_str!("templates/search_promotion_edit.html"),
2069 ),
2070 (
2071 "rcms_admin/styleguide.html",
2072 include_str!("templates/styleguide.html"),
2073 ),
2074 (
2075 "rcms_admin/dashboard.html",
2076 include_str!("templates/dashboard.html"),
2077 ),
2078 (
2079 "rcms_admin/redirect_import.html",
2080 include_str!("templates/redirect_import.html"),
2081 ),
2082 (
2083 "rcms_admin/snippet_import.html",
2084 include_str!("templates/snippet_import.html"),
2085 ),
2086 (
2087 "rcms_admin/site_settings_list.html",
2088 include_str!("templates/site_settings_list.html"),
2089 ),
2090 (
2091 "rcms_admin/template_list.html",
2092 include_str!("templates/template_list.html"),
2093 ),
2094 (
2095 "rcms_admin/template_form.html",
2096 include_str!("templates/template_form.html"),
2097 ),
2098 (
2099 "rcms_admin/page_type_template_form.html",
2100 include_str!("templates/page_type_template_form.html"),
2101 ),
2102 (
2103 "rcms_admin/site_setting_form.html",
2104 include_str!("templates/site_setting_form.html"),
2105 ),
2106 (
2110 "rcms/view_password.html",
2111 include_str!("templates/view_password.html"),
2112 ),
2113 (
2114 "rcms_admin/redirect_list.html",
2115 include_str!("templates/redirect_list.html"),
2116 ),
2117 (
2118 "rcms_admin/redirect_form.html",
2119 include_str!("templates/redirect_form.html"),
2120 ),
2121 (
2122 "rcms_admin/settings.html",
2123 include_str!("templates/settings.html"),
2124 ),
2125 (
2126 "rcms_admin/history.html",
2127 include_str!("templates/history.html"),
2128 ),
2129 (
2130 "rcms_admin/navigation_list.html",
2131 include_str!("templates/navigation_list.html"),
2132 ),
2133 (
2134 "rcms_admin/navigation_edit.html",
2135 include_str!("templates/navigation_edit.html"),
2136 ),
2137 (
2138 "rcms_admin/page_types.html",
2139 include_str!("templates/page_types.html"),
2140 ),
2141 (
2142 "rcms_admin/page_type_builder.html",
2143 include_str!("templates/page_type_builder.html"),
2144 ),
2145 (
2146 "rcms_admin/components_list.html",
2147 include_str!("templates/components_list.html"),
2148 ),
2149 (
2150 "rcms_admin/schema_page.html",
2151 include_str!("templates/schema_page.html"),
2152 ),
2153 (
2154 "rcms_admin/page_type_form.html",
2155 include_str!("templates/page_type_form.html"),
2156 ),
2157 (
2158 "rcms_admin/component_builder.html",
2159 include_str!("templates/component_builder.html"),
2160 ),
2161 (
2162 "rcms_admin/users_list.html",
2163 include_str!("templates/users_list.html"),
2164 ),
2165 (
2166 "rcms_admin/user_form.html",
2167 include_str!("templates/user_form.html"),
2168 ),
2169 (
2170 "rcms_admin/roles_list.html",
2171 include_str!("templates/roles_list.html"),
2172 ),
2173 (
2174 "rcms_admin/permissions_overview.html",
2175 include_str!("templates/permissions_overview.html"),
2176 ),
2177 (
2178 "rcms_admin/role_form.html",
2179 include_str!("templates/role_form.html"),
2180 ),
2181 (
2182 "rcms_admin/media_unused.html",
2183 include_str!("templates/media_unused.html"),
2184 ),
2185 (
2186 "rcms_admin/media_edit.html",
2187 include_str!("templates/media_edit.html"),
2188 ),
2189 (
2190 "rcms_admin/collection_permissions.html",
2191 include_str!("templates/collection_permissions.html"),
2192 ),
2193 (
2194 "rcms_admin/collections_list.html",
2195 include_str!("templates/collections_list.html"),
2196 ),
2197 (
2199 "rcms_admin/taxonomies_list.html",
2200 include_str!("templates/taxonomies_list.html"),
2201 ),
2202 (
2203 "rcms_admin/category_tree.html",
2204 include_str!("templates/category_tree.html"),
2205 ),
2206 (
2207 "rcms_admin/category_form.html",
2208 include_str!("templates/category_form.html"),
2209 ),
2210 ("login.html", include_str!("templates/login.html")),
2216 (
2217 "rcms_admin/password_reset_request.html",
2218 include_str!("templates/password_reset_request.html"),
2219 ),
2220 (
2221 "rcms_admin/password_reset_sent.html",
2222 include_str!("templates/password_reset_sent.html"),
2223 ),
2224 (
2225 "rcms_admin/password_reset_confirm.html",
2226 include_str!("templates/password_reset_confirm.html"),
2227 ),
2228 (
2229 "rcms_admin/password_reset_done.html",
2230 include_str!("templates/password_reset_done.html"),
2231 ),
2232 (
2233 "rcms_admin/no_access.html",
2234 include_str!("templates/no_access.html"),
2235 ),
2236 (
2237 "rcms_admin/account_preferences.html",
2238 include_str!("templates/account_preferences.html"),
2239 ),
2240 (
2241 "rcms_admin/_breadcrumbs.html",
2242 include_str!("templates/_breadcrumbs.html"),
2243 ),
2244 (
2250 "blocks/heading.html",
2251 include_str!("templates/blocks/heading.html"),
2252 ),
2253 (
2254 "blocks/paragraph.html",
2255 include_str!("templates/blocks/paragraph.html"),
2256 ),
2257 (
2258 "blocks/image.html",
2259 include_str!("templates/blocks/image.html"),
2260 ),
2261 (
2262 "blocks/quote.html",
2263 include_str!("templates/blocks/quote.html"),
2264 ),
2265 (
2266 "blocks/embed.html",
2267 include_str!("templates/blocks/embed.html"),
2268 ),
2269 (
2270 "blocks/code.html",
2271 include_str!("templates/blocks/code.html"),
2272 ),
2273 (
2275 "blocks/text.html",
2276 include_str!("templates/blocks/text.html"),
2277 ),
2278 (
2279 "blocks/boolean.html",
2280 include_str!("templates/blocks/boolean.html"),
2281 ),
2282 (
2283 "blocks/date.html",
2284 include_str!("templates/blocks/date.html"),
2285 ),
2286 (
2287 "blocks/datetime.html",
2288 include_str!("templates/blocks/datetime.html"),
2289 ),
2290 (
2291 "blocks/email.html",
2292 include_str!("templates/blocks/email.html"),
2293 ),
2294 ("blocks/url.html", include_str!("templates/blocks/url.html")),
2295 (
2296 "blocks/integer.html",
2297 include_str!("templates/blocks/integer.html"),
2298 ),
2299 (
2300 "blocks/choice.html",
2301 include_str!("templates/blocks/choice.html"),
2302 ),
2303 (
2304 "blocks/table.html",
2305 include_str!("templates/blocks/table.html"),
2306 ),
2307 (
2309 "blocks/float.html",
2310 include_str!("templates/blocks/float.html"),
2311 ),
2312 (
2313 "blocks/decimal.html",
2314 include_str!("templates/blocks/decimal.html"),
2315 ),
2316 (
2317 "blocks/regex.html",
2318 include_str!("templates/blocks/regex.html"),
2319 ),
2320 (
2321 "blocks/rich_text.html",
2322 include_str!("templates/blocks/rich_text.html"),
2323 ),
2324 (
2325 "blocks/typed_table_row.html",
2326 include_str!("templates/blocks/typed_table_row.html"),
2327 ),
2328 (
2329 "blocks/typed_table.html",
2330 include_str!("templates/blocks/typed_table.html"),
2331 ),
2332 (
2333 "blocks/time.html",
2334 include_str!("templates/blocks/time.html"),
2335 ),
2336 (
2337 "blocks/multiple_choice.html",
2338 include_str!("templates/blocks/multiple_choice.html"),
2339 ),
2340 (
2341 "blocks/static.html",
2342 include_str!("templates/blocks/static.html"),
2343 ),
2344 (
2345 "blocks/raw_html.html",
2346 include_str!("templates/blocks/raw_html.html"),
2347 ),
2348 (
2349 "blocks/page_chooser.html",
2350 include_str!("templates/blocks/page_chooser.html"),
2351 ),
2352 (
2353 "blocks/snippet_chooser.html",
2354 include_str!("templates/blocks/snippet_chooser.html"),
2355 ),
2356 (
2357 "blocks/document_chooser.html",
2358 include_str!("templates/blocks/document_chooser.html"),
2359 ),
2360 ])?;
2361
2362 if !tera.get_template_names().any(|n| n == "error_page.html") {
2369 tera.add_raw_template("error_page.html", include_str!("templates/error_page.html"))?;
2370 }
2371
2372 let override_root = std::path::PathBuf::from("templates/cms_admin");
2377 if override_root.is_dir() {
2378 let count = load_template_overrides(&override_root, "", tera)?;
2379 if count > 0 {
2380 tracing::info!(
2381 target: "rustango_cms::admin",
2382 count,
2383 path = %override_root.display(),
2384 "loaded admin template overrides",
2385 );
2386 }
2387 }
2388 Ok(())
2389}
2390
2391fn load_template_overrides(
2403 dir: &std::path::Path,
2404 prefix: &str,
2405 tera: &mut Tera,
2406) -> Result<usize, tera::Error> {
2407 let mut count = 0;
2408 let entries = std::fs::read_dir(dir)
2409 .map_err(|e| tera::Error::msg(format!("read_dir {}: {e}", dir.display())))?;
2410 for entry in entries {
2411 let entry = entry
2412 .map_err(|e| tera::Error::msg(format!("read_dir entry in {}: {e}", dir.display())))?;
2413 let path = entry.path();
2414 let name = match entry.file_name().into_string() {
2415 Ok(n) => n,
2416 Err(_) => continue,
2417 };
2418 if path.is_dir() {
2419 let nested_prefix = if prefix.is_empty() {
2420 name.clone()
2421 } else {
2422 format!("{prefix}/{name}")
2423 };
2424 count += load_template_overrides(&path, &nested_prefix, tera)?;
2425 } else if path.extension().and_then(|e| e.to_str()) == Some("html") {
2426 let template_name = derive_override_template_name(prefix, &name);
2427 let source = std::fs::read_to_string(&path)
2428 .map_err(|e| tera::Error::msg(format!("read {}: {e}", path.display())))?;
2429 tera.add_raw_template(&template_name, &source)?;
2430 tracing::info!(
2431 target: "rustango_cms::admin",
2432 path = %path.display(),
2433 template = %template_name,
2434 "registered admin template override",
2435 );
2436 count += 1;
2437 }
2438 }
2439 Ok(count)
2440}
2441
2442fn derive_override_template_name(prefix: &str, file_name: &str) -> String {
2448 if prefix.is_empty() {
2449 match file_name {
2453 "_auth_layout.html" => "rcms_admin/_auth_layout.html".to_owned(),
2454 other => other.to_owned(),
2455 }
2456 } else {
2457 format!("{prefix}/{file_name}")
2458 }
2459}
2460
2461#[derive(Debug, thiserror::Error)]
2464pub(crate) enum AdminError {
2465 #[error(transparent)]
2466 Tree(#[from] TreeError),
2467 #[error(transparent)]
2468 Exec(#[from] rustango::sql::ExecError),
2469 #[error(transparent)]
2470 Sqlx(#[from] rustango::sql::sqlx::Error),
2471 #[error(transparent)]
2472 Tera(#[from] tera::Error),
2473 #[error("page {0} not found")]
2474 NotFound(i64),
2475 #[error("upload failed: {0}")]
2476 Upload(String),
2477 #[error("{0}")]
2478 Validation(String),
2479}
2480
2481impl IntoResponse for AdminError {
2482 fn into_response(self) -> Response {
2483 let status = match &self {
2484 AdminError::NotFound(_) => StatusCode::NOT_FOUND,
2485 AdminError::Tree(TreeError::DisallowedChildType { .. })
2486 | AdminError::Tree(TreeError::DisallowedParentType { .. })
2487 | AdminError::Tree(TreeError::CycleAttempt) => StatusCode::BAD_REQUEST,
2488 AdminError::Upload(_) => StatusCode::BAD_REQUEST,
2489 AdminError::Validation(_) => StatusCode::BAD_REQUEST,
2490 _ => StatusCode::INTERNAL_SERVER_ERROR,
2491 };
2492 let mut chain = self.to_string();
2493 let mut src: Option<&dyn std::error::Error> = std::error::Error::source(&self);
2494 while let Some(s) = src {
2495 chain.push_str("\n caused by: ");
2496 chain.push_str(&s.to_string());
2497 src = s.source();
2498 }
2499 if status != StatusCode::INTERNAL_SERVER_ERROR {
2500 return (status, chain).into_response();
2502 }
2503 let reference = crate::mcp::mint_uuid4();
2507 tracing::error!(target: "rustango_cms::admin", error_ref = %reference, "{chain}");
2508 (status, format!("Internal server error (ref {reference})")).into_response()
2509 }
2510}
2511
2512#[derive(Debug, Deserialize)]
2514pub struct PageForm {
2515 pub title: String,
2516 pub slug: String,
2517 pub page_type_id: i64,
2518 pub status: String,
2519 #[serde(rename = "_action", default)]
2524 pub action: String,
2525 #[serde(default)]
2526 pub seo_title: String,
2527 #[serde(default)]
2528 pub seo_description: String,
2529 #[serde(default)]
2530 pub robots_index: Option<String>,
2531 #[serde(default)]
2532 pub sitemap_priority: Option<f32>,
2533 #[serde(default)]
2537 pub show_in_menus: Option<String>,
2538 #[serde(default)]
2542 pub parent_id: Option<i64>,
2543 #[serde(default, deserialize_with = "deserialize_optional_i64")]
2546 pub theme_id: Option<i64>,
2547 #[serde(default)]
2553 pub go_live_at: Option<String>,
2554 #[serde(default)]
2556 pub expire_at: Option<String>,
2557 #[serde(default)]
2562 pub preview_path: String,
2563 #[serde(default)]
2566 pub template_override: String,
2567 #[serde(default)]
2571 pub og_title: String,
2572 #[serde(default)]
2573 pub og_description: String,
2574 #[serde(default, deserialize_with = "deserialize_optional_i64")]
2575 pub og_image_media_id: Option<i64>,
2576 #[serde(default)]
2577 pub twitter_card: Option<String>,
2578 #[serde(default)]
2581 pub tags: Option<String>,
2582 #[serde(default)]
2584 pub categories: Option<String>,
2585}
2586
2587pub(crate) fn deserialize_optional_i64<'de, D>(deserializer: D) -> Result<Option<i64>, D::Error>
2591where
2592 D: serde::Deserializer<'de>,
2593{
2594 use serde::Deserialize as _;
2595 let s = String::deserialize(deserializer)?;
2596 if s.is_empty() || s == "0" {
2597 return Ok(None);
2598 }
2599 s.parse::<i64>().map(Some).map_err(serde::de::Error::custom)
2600}
2601
2602impl PageForm {
2603 fn parsed_status(&self) -> PageStatus {
2607 match self.status.as_str() {
2608 "published" => PageStatus::Published,
2609 "scheduled" => PageStatus::Scheduled,
2610 "archived" => PageStatus::Archived,
2611 _ => PageStatus::Draft,
2612 }
2613 }
2614
2615 fn parsed_robots_index(&self) -> bool {
2618 self.robots_index.is_some()
2619 }
2620
2621 fn parsed_sitemap_priority(&self) -> f32 {
2622 self.sitemap_priority.unwrap_or(0.5)
2623 }
2624
2625 fn parsed_show_in_menus(&self) -> bool {
2626 self.show_in_menus.is_some()
2627 }
2628
2629 fn parsed_go_live_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
2635 parse_datetime_local(self.go_live_at.as_deref())
2636 }
2637
2638 fn parsed_expire_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
2639 parse_datetime_local(self.expire_at.as_deref())
2640 }
2641}
2642
2643fn parse_datetime_local(raw: Option<&str>) -> Option<chrono::DateTime<chrono::Utc>> {
2644 let raw = raw?.trim();
2645 if raw.is_empty() {
2646 return None;
2647 }
2648 if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(raw) {
2651 return Some(dt.with_timezone(&chrono::Utc));
2652 }
2653 if let Some(utc) = raw.strip_suffix('Z') {
2654 return parse_datetime_local(Some(utc));
2655 }
2656 chrono::NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M")
2659 .or_else(|_| chrono::NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M:%S"))
2660 .ok()
2661 .map(|naive| chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(naive, chrono::Utc))
2662}
2663
2664#[cfg(test)]
2665mod datetime_input_tests {
2666 use super::parse_datetime_local;
2667
2668 #[test]
2671 fn utc_offset_and_bare_values_parse_to_the_same_instant() {
2672 let want = chrono::DateTime::parse_from_rfc3339("2026-12-01T12:00:00Z")
2673 .unwrap()
2674 .with_timezone(&chrono::Utc);
2675 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 "] {
2676 assert_eq!(parse_datetime_local(Some(raw)), Some(want), "{raw}");
2677 }
2678 assert_eq!(parse_datetime_local(Some("")), None);
2679 assert_eq!(parse_datetime_local(Some("tomorrow")), None);
2680 }
2681}
2682
2683#[cfg(test)]
2684mod admin_error_tests {
2685 use super::AdminError;
2686 use axum::response::IntoResponse as _;
2687
2688 async fn body(e: AdminError) -> (u16, String) {
2689 let resp = e.into_response();
2690 let status = resp.status().as_u16();
2691 let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16).await.expect("body");
2692 (status, String::from_utf8(bytes.to_vec()).expect("utf8"))
2693 }
2694
2695 #[tokio::test]
2698 async fn server_errors_hide_their_cause_and_client_errors_do_not() {
2699 let tera_err = tera::Tera::one_off("{{ secret_column | nope }}", &tera::Context::new(), false)
2700 .expect_err("bad template");
2701 let (status, text) = body(AdminError::Tera(tera_err)).await;
2702 assert_eq!(status, 500);
2703 assert!(text.starts_with("Internal server error (ref "), "{text}");
2704 assert!(!text.contains("secret_column") && !text.contains("nope"), "{text}");
2705
2706 let (status, text) = body(AdminError::Validation("slug is taken".into())).await;
2707 assert_eq!(status, 400);
2708 assert!(text.contains("slug is taken"));
2709 }
2710}
2711
2712#[cfg(test)]
2713mod template_shape_tests {
2714 #[test]
2717 fn json_script_cannot_close_the_script_element() {
2718 let hostile = serde_json::json!([{
2719 "name": "</script><script>alert('x')</script> & <!--",
2720 }]);
2721 let mut tera = tera::Tera::default();
2722 super::register_templates(&mut tera).expect("register");
2723 tera.add_raw_template("t", "<script>const X = {{ v | json_script }};</script>")
2724 .expect("template");
2725 let mut ctx = tera::Context::new();
2726 ctx.insert("v", &hostile);
2727 let out = tera.render("t", &ctx).expect("render");
2728 let body = out
2729 .strip_prefix("<script>const X = ")
2730 .and_then(|r| r.strip_suffix(";</script>"))
2731 .expect("one script element");
2732 assert!(!body.contains('<') && !body.contains('>') && !body.contains('\''), "{body}");
2733 let back: serde_json::Value = serde_json::from_str(body).expect("still JSON");
2734 assert_eq!(back, hostile);
2735 }
2736
2737 #[test]
2740 fn no_admin_template_inlines_raw_json() {
2741 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/admin/templates");
2742 let offenders: Vec<String> = std::fs::read_dir(&dir)
2743 .expect("read templates dir")
2744 .filter_map(|e| {
2745 let path = e.expect("dir entry").path();
2746 let src = std::fs::read_to_string(&path).ok()?;
2747 src.contains("json_encode | safe")
2748 .then(|| path.file_name().unwrap().to_string_lossy().to_string())
2749 })
2750 .collect();
2751 assert!(offenders.is_empty(), "use `| json_script` instead: {offenders:?}");
2752 }
2753
2754 #[test]
2765 fn page_descriptions_come_from_the_shared_intro_card() {
2766 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/admin/templates");
2767 let mut offenders = Vec::new();
2768 let mut checked = 0;
2769 for entry in std::fs::read_dir(&dir).expect("read templates dir") {
2770 let path = entry.expect("dir entry").path();
2771 if path.extension().and_then(|e| e.to_str()) != Some("html") {
2772 continue;
2773 }
2774 let src = std::fs::read_to_string(&path).expect("read template");
2775 let name = path.file_name().unwrap().to_string_lossy().to_string();
2776 if src.contains("rcms_admin/_list_base.html") {
2777 checked += 1;
2779 continue;
2780 }
2781 let Some(rest) = src.split_once("{% block content %}") else {
2782 continue;
2783 };
2784 checked += 1;
2785 let head = rest.1.trim_start();
2786 if head.starts_with("<p class=\"rcms-hint") {
2787 offenders.push(format!(
2788 "{name}: bare <p class=\"rcms-hint\"> opens the content \
2789 column — extend rcms_admin/_list_base.html and put the \
2790 prose in {{% block description %}}"
2791 ));
2792 } else if rest
2793 .1
2794 .contains("<div class=\"rcms-card\">\n <p class=\"rcms-hint")
2795 {
2796 offenders.push(format!(
2800 "{name}: hand-rolled intro card — extend \
2801 rcms_admin/_list_base.html instead"
2802 ));
2803 }
2804 }
2805 assert!(
2806 checked > 40,
2807 "expected to scan most admin templates, scanned {checked} — \
2808 the `{{% block content %}}` probe is broken"
2809 );
2810 assert!(
2811 offenders.is_empty(),
2812 "{} page(s) don't use the shared intro card:\n{}",
2813 offenders.len(),
2814 offenders.join("\n")
2815 );
2816 }
2817
2818 #[test]
2827 fn get_env_is_disabled_in_the_render_engine() {
2828 let secret = std::env::var("CARGO_PKG_NAME").expect("cargo sets CARGO_PKG_NAME");
2829 let mut tera = tera::Tera::default();
2830 super::register_templates(&mut tera).expect("register_templates");
2831 tera.add_raw_template("ssti.html", r#"{{ get_env(name="CARGO_PKG_NAME") }}"#)
2832 .expect("add template");
2833 match tera.render("ssti.html", &tera::Context::new()) {
2834 Err(_) => {}
2836 Ok(out) => assert!(
2839 !out.contains(&secret),
2840 "get_env leaked the process environment into a template: {out}"
2841 ),
2842 }
2843 }
2844}