1mod audit;
18pub mod bootstrap;
19mod bulk;
20mod clientip;
21pub mod descriptor;
22mod error;
23mod export;
24pub mod field;
25pub mod form;
26pub mod html;
27pub mod http_cache;
28mod icons;
29pub(crate) mod keyed;
30pub mod list;
31pub mod persist;
32pub mod picker;
33pub mod plugins;
34mod roles;
35mod routemap;
36pub mod routes;
37mod session;
38pub mod settings;
39mod sql;
40mod upload;
41mod users;
42
43pub use axum;
51
52pub use bootstrap::{AppConfig, Bootstrap, BootstrapCtx, DEFAULT_ENV_PREFIX};
53pub use error::AdminError;
54pub use session::{FlashLevel, SessionHandle};
55pub use upload::VerifiedUpload;
56
57use std::collections::HashMap;
58use std::sync::{Arc, RwLock};
59
60use askama::Template;
61use axum::body::Body;
62use axum::extract::{Path, Query, Request, State};
63use axum::http::{header, HeaderMap};
64use axum::middleware::{self, Next};
65use axum::response::{Html, IntoResponse, Redirect, Response};
66use axum::routing::{any, get, post};
67use axum::{Extension, Form, Router};
68use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
69use chrono_tz::{Tz, TZ_VARIANTS};
70use laterite_auth::{AuthService, AuthenticatedUser, NewOperator, PermissionSet, RequestContext};
71use laterite_core::{t, CatalogStore, Db, Text, Translator};
72use serde::{Deserialize, Serialize};
73
74pub trait AdminRegistry {
80 fn add_resource(&mut self, resource: Resource);
82 fn add_permission(&mut self, permission: Permission);
84 fn add_settings(&mut self, item: settings::SettingsItem);
86 fn add_picker_source(&mut self, source: picker::PickerSourceReg);
88 fn add_persister(&mut self, persister: persist::PersisterReg);
90 fn add_field_type(&mut self, field_type: field::FieldTypeReg);
92 fn add_screen(&mut self, screen: routes::ScreenReg);
95 fn add_public_route(&mut self, route: routes::PublicRouteReg);
98}
99
100impl AdminRegistry for laterite_core::Registry {
101 fn add_resource(&mut self, resource: Resource) {
102 self.add(resource);
103 }
104 fn add_permission(&mut self, permission: Permission) {
105 self.add(permission);
106 }
107 fn add_settings(&mut self, item: settings::SettingsItem) {
108 self.add(item);
109 }
110 fn add_picker_source(&mut self, source: picker::PickerSourceReg) {
111 self.add(source);
112 }
113 fn add_screen(&mut self, screen: routes::ScreenReg) {
114 self.add(screen);
115 }
116 fn add_public_route(&mut self, route: routes::PublicRouteReg) {
117 self.add(route);
118 }
119 fn add_persister(&mut self, persister: persist::PersisterReg) {
120 self.add(persister);
121 }
122 fn add_field_type(&mut self, field_type: field::FieldTypeReg) {
123 self.add(field_type);
124 }
125}
126
127const SESSION_COOKIE: &str = "laterite_session";
128const REMEMBER_COOKIE: &str = "laterite_remember";
132
133pub(crate) const ICON_SPRITE: &str = "icons.svg";
136
137#[derive(Clone)]
139pub(crate) struct AdminState {
140 auth: AuthService,
141 db: Db,
142 nav: Arc<Vec<NavLink>>,
143 settings: Arc<Vec<settings::SettingsItem>>,
144 permissions: Arc<Vec<Permission>>,
145 admin_path: Arc<str>,
149 secure_cookie: bool,
150 trusted_proxies: Arc<Vec<ipnet::IpNet>>,
152 icons: Arc<laterite_core::icons::IconSet>,
154 sprite_url: Arc<str>,
156 origin: Arc<str>,
158 timezone: Tz,
159 default_locale: Arc<str>,
163 catalogs: Arc<CatalogStore>,
166 app_name: String,
169 brand_cache: Arc<RwLock<Option<String>>>,
173 asset_urls: Arc<AssetUrls>,
175 field_types: Arc<field::FieldRegistry>,
178 column_types: Arc<list::ColumnRegistry>,
181 plugin_defined: Arc<laterite_core::Registry>,
184 assets: Arc<AssetRegistry>,
186 pickers: Arc<picker::PickerRegistry>,
189 overrides: Arc<dyn field::OverrideResolver>,
193}
194
195impl AdminState {
196 #[cfg(test)]
197 pub(crate) fn new(auth: AuthService, db: Db) -> Self {
198 Self {
199 auth,
200 db,
201 nav: Arc::new(Vec::new()),
202 settings: Arc::new(Vec::new()),
203 permissions: Arc::new(builtin_permissions()),
204 trusted_proxies: Arc::new(Vec::new()),
205 icons: Arc::new(laterite_core::icons::IconSet::new()),
206 sprite_url: Arc::from(""),
207 admin_path: Arc::from("/admin"),
208 secure_cookie: false,
209 origin: Arc::from(""),
210 timezone: Tz::UTC,
211 default_locale: Arc::from("en"),
212 catalogs: Arc::new(CatalogStore::default()),
213 app_name: "Laterite".to_string(),
214 brand_cache: Arc::new(RwLock::new(None)),
215 field_types: Arc::new(field::builtin_registry()),
216 column_types: Arc::new(list::builtin_column_registry()),
217 plugin_defined: Arc::new(laterite_core::Registry::new()),
218 assets: Arc::new(builtin_assets()),
219 asset_urls: Arc::new(asset_urls(&builtin_assets())),
220 pickers: Arc::new(picker::PickerRegistry::new()),
221 overrides: Arc::new(field::NoOverrides),
222 }
223 }
224
225 async fn brand(&self) -> String {
229 {
230 let cached = self.brand_cache.read().unwrap().clone();
231 if let Some(name) = cached {
232 return name;
233 }
234 }
235 let resolved = match settings::store::load::<settings::BrandSetting>(&self.db).await {
236 Ok(brand) if !brand.app_name.trim().is_empty() => brand.app_name,
237 _ => self.app_name.clone(),
238 };
239 *self.brand_cache.write().unwrap() = Some(resolved.clone());
240 resolved
241 }
242
243 fn invalidate_brand(&self) {
245 *self.brand_cache.write().unwrap() = None;
246 }
247}
248
249#[derive(Clone)]
255#[non_exhaustive]
256pub struct AdminConfig {
257 pub secure_cookie: bool,
260 pub trusted_proxies: Vec<String>,
264 pub timezone: String,
268 pub locale: String,
272 pub app_name: String,
276 pub path: String,
280 pub origin: String,
285}
286
287impl Default for AdminConfig {
288 fn default() -> Self {
289 Self {
290 secure_cookie: false,
291 trusted_proxies: Vec::new(),
292 timezone: "UTC".to_string(),
293 locale: "en".to_string(),
294 app_name: "Laterite".to_string(),
295 path: "/admin".to_string(),
296 origin: String::new(),
297 }
298 }
299}
300
301#[derive(Clone)]
302struct NavLink {
303 label: Text,
304 path: String,
305 icon: Option<&'static str>,
308}
309
310#[derive(Clone)]
315pub(crate) struct Shell {
316 pub(crate) base: String,
320 brand: String,
324 nav: Vec<NavView>,
325 full_name: String,
326 initial: String,
327 tz: Tz,
331 i18n: Translator,
335 sidebar: Vec<settings::CategoryView>,
339 pub(crate) icon_set: Arc<laterite_core::icons::IconSet>,
341 pub(crate) sprite_url: Arc<str>,
344 site_url: String,
348 asset_urls: Arc<AssetUrls>,
352 pub(crate) csrf_token: String,
356 pub(crate) flash: Vec<FlashLine>,
360 pub(crate) assets: Vec<PageAsset>,
364}
365
366#[derive(Clone)]
368pub(crate) struct PageAsset {
369 pub(crate) url: String,
370 pub(crate) css: bool,
371}
372
373#[derive(Clone)]
376pub(crate) struct FlashLine {
377 pub(crate) level: session::FlashLevel,
378 pub(crate) text: String,
379 pub(crate) sticky: bool,
381}
382
383impl Shell {
384 #[allow(clippy::too_many_arguments)]
385 fn new(
386 base: &str,
387 brand: String,
388 nav: &[NavLink],
389 user: &AuthenticatedUser,
390 default_tz: Tz,
391 sidebar: Vec<settings::CategoryView>,
392 active_nav: Option<&str>,
393 csrf_token: String,
394 flash: Vec<session::Flash>,
395 i18n: Translator,
396 asset_urls: Arc<AssetUrls>,
397 site_url: String,
398 icon_set: Arc<laterite_core::icons::IconSet>,
399 sprite_url: Arc<str>,
400 ) -> Self {
401 let full_name = user.user.full_name();
402 let initial = full_name
403 .chars()
404 .next()
405 .map(|c| c.to_uppercase().to_string())
406 .unwrap_or_else(|| "?".to_string());
407 let flash = flash
410 .into_iter()
411 .map(|f| FlashLine {
412 sticky: f.sticky,
413 level: f.level,
414 text: i18n.t(&f.text),
415 })
416 .collect();
417 let nav = nav
418 .iter()
419 .map(|n| NavView {
420 label: i18n.t(&n.label),
421 path: n.path.clone(),
422 active: active_nav == Some(n.path.as_str()),
423 icon: n
424 .icon
425 .map(|name| icons::svg(&icon_set, &sprite_url, Some(name)))
426 .unwrap_or_default(),
427 })
428 .collect();
429 Shell {
430 asset_urls,
431 icon_set,
432 sprite_url,
433 site_url,
434 base: base.to_string(),
435 brand,
436 nav,
437 full_name,
438 initial,
439 tz: resolve_display_tz(user.user.timezone.as_deref(), default_tz),
440 i18n,
441 sidebar,
442 csrf_token,
443 flash,
444 assets: Vec::new(),
445 }
446 }
447
448 pub(crate) fn site_url(&self) -> &str {
450 &self.site_url
451 }
452
453 pub(crate) fn icon(&self, name: &str) -> String {
455 icons::svg(&self.icon_set, &self.sprite_url, Some(name))
456 }
457
458 pub(crate) fn asset(&self, key: &str) -> String {
463 match self.asset_urls.get(key) {
464 Some(path) => format!("{}/assets/{path}", self.base),
465 None => {
466 debug_assert!(false, "asset key `{key}` is not registered");
467 format!("{}/assets/{key}", self.base)
468 }
469 }
470 }
471
472 pub(crate) fn t(&self, source: &str) -> String {
475 self.i18n.t(&Text::dynamic(source))
476 }
477
478 pub(crate) fn tt(&self, text: &Text) -> String {
481 self.i18n.t(text)
482 }
483
484 pub(crate) fn i18n(&self) -> &Translator {
487 &self.i18n
488 }
489
490 pub(crate) fn locale(&self) -> &str {
492 self.i18n.locale()
493 }
494
495 pub(crate) fn tf(&self, source: &str, args: &[(&'static str, i64)]) -> String {
499 let mut text = Text::dynamic(source);
500 for (name, value) in args {
501 text = text.arg(*name, *value);
502 }
503 self.i18n.t(&text)
504 }
505
506 pub(crate) fn tfs(&self, source: &str, args: &[(&'static str, &str)]) -> String {
509 let mut text = Text::dynamic(source);
510 for (name, value) in args {
511 text = text.arg(*name, *value);
512 }
513 self.i18n.t(&text)
514 }
515
516 #[cfg(test)]
517 pub(crate) fn test() -> Self {
518 Shell {
519 asset_urls: Arc::new(asset_urls(&builtin_assets())),
520 icon_set: Arc::new(laterite_core::icons::IconSet::new()),
521 sprite_url: Arc::from("/admin/assets/icons.svg"),
522 site_url: "http://localhost".to_string(),
523 base: "/admin".to_string(),
524 brand: "Laterite".to_string(),
525 nav: Vec::new(),
526 full_name: "Test Operator".to_string(),
527 initial: "T".to_string(),
528 tz: Tz::UTC,
529 i18n: Translator::new("en"),
530 sidebar: Vec::new(),
531 csrf_token: "test-csrf-token".to_string(),
532 flash: Vec::new(),
533 assets: Vec::new(),
534 }
535 }
536}
537
538fn settings_context(
545 visible: &[settings::SettingsItem],
546 admin_path: &str,
547 path: &str,
548) -> (bool, Option<String>) {
549 if path == format!("{admin_path}/settings") {
550 return (true, None);
551 }
552 let own = visible
558 .iter()
559 .filter(|i| i.link.is_none())
560 .find(|i| path == format!("{admin_path}{}", i.route()))
561 .map(|i| i.code.clone());
562 if own.is_some() {
563 return (true, own);
564 }
565 let linked = visible
566 .iter()
567 .filter_map(|i| {
568 i.link
569 .as_deref()
570 .map(|link| (format!("{admin_path}{link}"), &i.code))
571 })
572 .filter(|(link, _)| path == link.as_str() || path.starts_with(&format!("{link}/")))
573 .max_by_key(|(link, _)| link.len())
574 .map(|(_, code)| code.clone());
575 (linked.is_some(), linked)
576}
577
578fn active_nav_path(
586 nav: &[NavLink],
587 admin_path: &str,
588 in_settings_context: bool,
589 path: &str,
590) -> Option<String> {
591 if in_settings_context {
592 return Some(format!("{admin_path}/settings"));
593 }
594 nav.iter()
595 .filter(|n| {
596 path == n.path || (n.path != admin_path && path.starts_with(&format!("{}/", n.path)))
597 })
598 .max_by_key(|n| n.path.len())
599 .map(|n| n.path.clone())
600}
601
602fn resolve_nav_context(
607 nav: &[NavLink],
608 items: &[settings::SettingsItem],
609 admin_path: &str,
610 perms: &PermissionSet,
611 path: &str,
612 tr: &Translator,
613 icons: icons::Icons<'_>,
614) -> (Vec<settings::CategoryView>, Option<String>) {
615 let visible = visible_settings(items, perms);
616 let (in_context, active) = settings_context(&visible, admin_path, path);
617 let sidebar = if in_context {
618 settings::sidebar_groups(&visible, admin_path, active.as_deref(), tr, icons)
619 } else {
620 Vec::new()
621 };
622 let active_nav = active_nav_path(nav, admin_path, in_context, path);
623 (sidebar, active_nav)
624}
625
626fn resolve_display_tz(preference: Option<&str>, default_tz: Tz) -> Tz {
630 preference
631 .and_then(|name| name.parse::<Tz>().ok())
632 .unwrap_or(default_tz)
633}
634
635fn zone_offered(name: &str) -> bool {
637 !matches!(name, "Asia/Jerusalem" | "Asia/Tel_Aviv")
638}
639
640fn base_lang(tag: &str) -> String {
643 tag.split(['-', '_'])
644 .next()
645 .unwrap_or(tag)
646 .to_ascii_lowercase()
647}
648
649fn is_serveable(base: &str, serveable: &[String]) -> bool {
655 base == "en" || base == laterite_core::PSEUDO_LOCALE || serveable.iter().any(|l| l == base)
656}
657
658fn default_locale(configured: &str, serveable: &[String]) -> String {
661 let base = base_lang(configured);
662 if is_serveable(&base, serveable) {
663 base
664 } else {
665 "en".to_string()
666 }
667}
668
669fn offered_locales(catalogs: &CatalogStore) -> Vec<String> {
673 let mut out = vec!["en".to_string()];
674 out.extend(catalogs.locales());
675 out
676}
677
678fn locale_name(code: &str) -> String {
683 if code == "en" {
684 "English".to_string()
685 } else {
686 code.to_string()
687 }
688}
689
690fn parse_accept_language(header: &str) -> Vec<String> {
693 let mut items: Vec<(f32, String)> = header
694 .split(',')
695 .filter_map(|part| {
696 let mut bits = part.split(';');
697 let tag = bits.next()?.trim();
698 if tag.is_empty() || tag == "*" {
699 return None;
700 }
701 let q = bits
702 .find_map(|p| p.trim().strip_prefix("q="))
703 .and_then(|q| q.parse::<f32>().ok())
704 .unwrap_or(1.0);
705 Some((q, tag.to_string()))
706 })
707 .collect();
708 items.sort_by(|a, b| b.0.total_cmp(&a.0));
710 items.into_iter().map(|(_, tag)| tag).collect()
711}
712
713fn resolve_locale_chain(
719 preference: Option<&str>,
720 accept_language: Option<&str>,
721 default: &str,
722 serveable: &[String],
723) -> Vec<String> {
724 let mut chain: Vec<String> = Vec::new();
725 let consider = |tag: &str, chain: &mut Vec<String>| {
726 let base = base_lang(tag);
727 if is_serveable(&base, serveable) && !chain.contains(&base) {
728 chain.push(base);
729 }
730 };
731 if let Some(pref) = preference {
732 consider(pref, &mut chain);
733 }
734 if let Some(header) = accept_language {
735 for tag in parse_accept_language(header) {
736 consider(&tag, &mut chain);
737 }
738 }
739 consider(default, &mut chain);
740 consider("en", &mut chain);
743 chain
744}
745
746fn pre_auth_translator(state: &AdminState, headers: &HeaderMap) -> Translator {
750 let accept = headers.get("accept-language").and_then(|v| v.to_str().ok());
751 let serveable = state.catalogs.locales();
752 let chain = resolve_locale_chain(None, accept, &state.default_locale, &serveable);
753 Translator::with_chain(chain, state.catalogs.clone())
754}
755
756#[derive(Serialize)]
764#[non_exhaustive]
765pub struct Resource {
766 pub base_path: String,
772 pub nav_label: Text,
774 pub list: list::ListConfig,
775 pub form: Option<form::FormConfig>,
776 pub permission: Option<String>,
783}
784
785#[derive(Clone, Serialize)]
790#[non_exhaustive]
791pub struct Permission {
792 pub code: String,
793 pub label: Text,
795 pub group: Text,
796 pub default_roles: Vec<String>,
799 pub renamed_from: Vec<String>,
802}
803
804pub use laterite_auth::{ROLE_ADMIN, ROLE_EDITOR};
805
806impl Permission {
807 pub fn new(code: impl Into<String>, label: impl Into<Text>, group: impl Into<Text>) -> Self {
810 Self {
811 code: code.into(),
812 label: label.into(),
813 group: group.into(),
814 default_roles: Vec::new(),
815 renamed_from: Vec::new(),
816 }
817 }
818
819 pub fn renamed_from<I, S>(mut self, codes: I) -> Self
825 where
826 I: IntoIterator<Item = S>,
827 S: Into<String>,
828 {
829 self.renamed_from = codes.into_iter().map(Into::into).collect();
830 self
831 }
832
833 pub fn roles<I, S>(mut self, roles: I) -> Self
836 where
837 I: IntoIterator<Item = S>,
838 S: Into<String>,
839 {
840 self.default_roles = roles.into_iter().map(Into::into).collect();
841 self
842 }
843}
844
845pub fn permission_renames(contributed: &[Permission]) -> Vec<(String, String)> {
851 let permissions: Vec<Permission> = builtin_permissions()
852 .into_iter()
853 .chain(contributed.iter().cloned())
854 .collect();
855 let mut out: Vec<(String, String)> = Vec::new();
856 for permission in &permissions {
857 for old in &permission.renamed_from {
858 if let Some((_, taken)) = out.iter().find(|(o, _)| o == old) {
859 panic!(
860 "permissions `{taken}` and `{}` both claim the old code `{old}`",
861 permission.code
862 );
863 }
864 if permissions.iter().any(|p| &p.code == old) {
865 panic!(
866 "permission `{}` claims `{old}` as an old code, but `{old}` is still registered",
867 permission.code
868 );
869 }
870 out.push((old.clone(), permission.code.clone()));
871 }
872 }
873 out
874}
875
876pub fn system_roles(contributed: &[Permission]) -> Vec<laterite_auth::store::SystemRole<'static>> {
882 let permissions: Vec<Permission> = builtin_permissions()
885 .into_iter()
886 .chain(contributed.iter().cloned())
887 .collect();
888 let held = |role: &str| -> Vec<String> {
889 permissions
890 .iter()
891 .filter(|p| {
892 if p.default_roles.is_empty() {
893 role == ROLE_ADMIN
894 } else {
895 p.default_roles.iter().any(|r| r == role)
896 }
897 })
898 .map(|p| p.code.clone())
899 .collect()
900 };
901 vec![
902 laterite_auth::store::SystemRole {
903 code: ROLE_ADMIN,
904 name: "Administrator",
905 description: "Administers the panel itself: operators, roles and settings.",
906 permissions: held(ROLE_ADMIN),
907 },
908 laterite_auth::store::SystemRole {
909 code: ROLE_EDITOR,
910 name: "Editor",
911 description: "Works with the content the application declares.",
912 permissions: held(ROLE_EDITOR),
913 },
914 ]
915}
916
917impl Resource {
918 pub fn new(
923 base_path: impl Into<String>,
924 nav_label: impl Into<Text>,
925 list: list::ListConfig,
926 ) -> Self {
927 Self {
928 base_path: base_path.into(),
929 nav_label: nav_label.into(),
930 list,
931 form: None,
932 permission: None,
933 }
934 }
935
936 pub fn form(mut self, form: form::FormConfig) -> Self {
939 self.form = Some(form);
940 self
941 }
942
943 pub fn permission(mut self, permission: impl Into<String>) -> Self {
945 self.permission = Some(permission.into());
946 self
947 }
948}
949
950struct SystemRoleGuard;
956
957#[laterite_core::strata::async_trait]
958impl laterite_core::ModelListener for SystemRoleGuard {
959 async fn before_delete(
960 &self,
961 cx: &mut laterite_core::SaveCx<'_>,
962 rec: &laterite_core::Record,
963 ) -> Result<(), Text> {
964 let Some(id) = rec.id() else {
965 return Ok(());
966 };
967 let backend = cx.backend();
969 match laterite_auth::store::role_is_system_on(cx.conn(), backend, id).await {
970 Ok(true) => Err(t!(
971 "The framework maintains this role; it cannot be deleted."
972 )),
973 Err(_) => Err(t!(
975 "Could not check whether this role is maintained by the framework."
976 )),
977 Ok(false) => Ok(()),
978 }
979 }
980}
981
982fn builtin_permissions() -> Vec<Permission> {
985 vec![
988 Permission::new("backend.manage_users", "Manage backend users", "Backend"),
989 Permission::new("backend.manage_roles", "Manage roles", "Backend"),
990 Permission::new("backend.manage_branding", "Manage branding", "Backend"),
991 Permission::new(plugins::MANAGE_PERMISSION, "Manage plugins", "Backend"),
992 Permission::new("backend.view_audit_log", "View the audit log", "Backend"),
993 Permission::new("backend.view_access_log", "View the access log", "Backend"),
994 ]
995}
996
997pub fn descriptor_sources() -> Vec<String> {
1003 let mut out = Vec::new();
1004 out.extend(laterite_core::collect_sources(&builtin_resources()));
1005 out.extend(laterite_core::collect_sources(&builtin_settings()));
1006 out.extend(laterite_core::collect_sources(&builtin_permissions()));
1007 out.sort();
1008 out.dedup();
1009 out
1010}
1011
1012pub fn builtin_migrations() -> Vec<laterite_core::MigrationSet> {
1027 builtin_modules().iter().map(|m| m.migrations()).collect()
1028}
1029
1030pub fn builtin_modules() -> Vec<Box<dyn laterite_core::Module>> {
1034 vec![
1035 Box::new(laterite_auth::AuthModule),
1036 Box::new(settings::SettingsModule),
1037 Box::new(plugins::PluginsModule),
1038 ]
1039}
1040
1041#[derive(Default)]
1065pub struct Contributions {
1066 pub resources: Vec<Resource>,
1068 pub settings: Vec<settings::SettingsItem>,
1070 pub permissions: Vec<Permission>,
1072 pub picker_sources: Vec<picker::PickerSourceReg>,
1074 pub persisters: Vec<persist::PersisterReg>,
1076 pub listeners: Vec<laterite_core::ModelListenerReg>,
1078 pub field_types: Vec<field::FieldTypeReg>,
1082 pub column_types: Vec<list::ColumnTypeReg>,
1083 pub icons: Vec<(laterite_core::ModuleId, laterite_core::icons::IconReg)>,
1086 pub screens: Vec<routes::ScreenReg>,
1088 pub public_routes: Vec<routes::PublicRouteReg>,
1090 pub plugin_defined: Arc<laterite_core::Registry>,
1095}
1096
1097pub fn router(
1098 auth: AuthService,
1099 db: Db,
1100 contributions: Contributions,
1101 config: AdminConfig,
1102 catalogs: Arc<CatalogStore>,
1103) -> Router {
1104 let Contributions {
1105 resources: app_resources,
1106 settings: app_settings,
1107 permissions: app_permissions,
1108 picker_sources: app_picker_sources,
1109 persisters: app_persisters,
1110 listeners: app_listeners,
1111 field_types: app_field_types,
1112 column_types: app_column_types,
1113 icons: app_icons,
1114 screens: app_screens,
1115 public_routes: app_public,
1116 plugin_defined,
1117 } = contributions;
1118 let admin_path = normalize_path(&config.path);
1119
1120 let mut resources = builtin_resources();
1121 let mut app_resources = app_resources;
1122 for resource in resources.iter_mut().chain(app_resources.iter_mut()) {
1126 prefix_resource(&admin_path, resource);
1127 }
1128
1129 let mut settings = builtin_settings();
1130 settings.extend(app_settings);
1131 let mut app_listeners = app_listeners;
1134 app_listeners.insert(
1135 0,
1136 laterite_core::ModelListenerReg::for_entity("backend_roles", Arc::new(SystemRoleGuard)),
1137 );
1138
1139 let mut permissions = builtin_permissions();
1140 permissions.extend(app_permissions);
1141 let permission_codes: std::collections::HashSet<String> =
1143 permissions.iter().map(|p| p.code.clone()).collect();
1144
1145 let mut nav = vec![NavLink {
1149 label: "Dashboard".into(),
1150 path: admin_path.clone(),
1151 icon: Some("layout-dashboard"),
1152 }];
1153 for resource in &app_resources {
1154 nav.push(NavLink {
1155 label: resource.nav_label.clone(),
1156 path: resource.base_path.clone(),
1157 icon: None,
1158 });
1159 }
1160 for reg in &app_screens {
1163 if let Some(label) = ®.nav_label {
1164 nav.push(NavLink {
1165 label: label.clone(),
1166 path: format!("{admin_path}{}", reg.base_path),
1167 icon: None,
1168 });
1169 }
1170 }
1171 nav.push(NavLink {
1172 label: "Settings".into(),
1173 path: format!("{admin_path}/settings"),
1174 icon: Some("settings"),
1175 });
1176 resources.extend(app_resources);
1177
1178 let app_name = if config.app_name.trim().is_empty() {
1179 "Laterite".to_string()
1180 } else {
1181 config.app_name.clone()
1182 };
1183
1184 let mut pickers = picker::PickerRegistry::new();
1187 for reg in app_picker_sources {
1188 let name = reg.name.clone();
1189 if !field::is_name(&name, true) {
1190 panic!("invalid picker source name `{name}`");
1191 }
1192 if pickers.insert(name.clone(), reg).is_some() {
1193 panic!("duplicate picker source `{name}`");
1194 }
1195 }
1196
1197 let pickers = Arc::new(pickers);
1201 let mut field_types = field::builtin_registry();
1202 field_types.insert(
1203 "reference".to_string(),
1204 Arc::new(field::RefPickerField::new(pickers.clone())),
1205 );
1206
1207 let mut persisters = persist::PersisterRegistry::new();
1210 for reg in app_persisters {
1211 let name = reg.name.clone();
1212 if !field::is_name(&name, true) {
1213 panic!("invalid persister name `{name}`");
1214 }
1215 if persisters.insert(name.clone(), reg.persister).is_some() {
1216 panic!("duplicate persister `{name}`");
1217 }
1218 }
1219
1220 for reg in app_field_types {
1226 let name = reg.name().to_string();
1227 if !field::is_name(&name, true) {
1228 panic!("invalid field type name `{name}`");
1229 }
1230 if field_types.insert(name.clone(), reg.field_type).is_some() {
1231 panic!("duplicate field type `{name}`");
1232 }
1233 }
1234
1235 let mut icon_set = laterite_core::icons::IconSet::new();
1239 for (owner, reg) in app_icons {
1240 if let Err(e) = icon_set.add(owner.as_str(), ®) {
1241 panic!("module `{owner}` contributed an invalid icon: {e}");
1242 }
1243 }
1244
1245 let mut assets = builtin_assets();
1248 assets.insert(
1249 ICON_SPRITE,
1250 AdminAsset {
1251 mime: "image/svg+xml",
1252 bytes: std::borrow::Cow::Owned(icon_set.sprite().into_bytes()),
1253 },
1254 );
1255
1256 for item in &settings {
1260 icons::require(
1261 &icon_set,
1262 &format!("settings item `{}`", item.code),
1263 item.icon.as_deref(),
1264 );
1265 }
1266 for link in &nav {
1267 icons::require(&icon_set, &format!("menu entry `{}`", link.path), link.icon);
1268 }
1269
1270 let mut column_types = list::builtin_column_registry();
1274 for reg in app_column_types {
1275 let name = reg.name().to_string();
1276 if !field::is_name(&name, true) {
1277 panic!("invalid column type name `{name}`");
1278 }
1279 if column_types.insert(name.clone(), reg.column_type).is_some() {
1280 panic!("duplicate column type `{name}`");
1281 }
1282 }
1283
1284 let settings = Arc::new(settings);
1285 let asset_urls_arc = Arc::new(asset_urls(&assets));
1287 let sprite_url: Arc<str> = Arc::from(
1288 asset_urls_arc
1289 .get(ICON_SPRITE)
1290 .map(|p| format!("{admin_path}/assets/{p}"))
1291 .unwrap_or_default()
1292 .as_str(),
1293 );
1294 let icons_arc = Arc::new(icon_set);
1295 let state = AdminState {
1296 auth,
1297 db,
1298 nav: Arc::new(nav),
1299 settings: settings.clone(),
1300 permissions: Arc::new(permissions),
1301 admin_path: Arc::from(admin_path.as_str()),
1302 secure_cookie: config.secure_cookie,
1303 trusted_proxies: Arc::new(clientip::parse_trusted(&config.trusted_proxies)),
1304 icons: icons_arc.clone(),
1305 sprite_url: sprite_url.clone(),
1306 origin: Arc::from(config.origin.trim_end_matches('/')),
1307 timezone: config.timezone.parse().unwrap_or(Tz::UTC),
1308 default_locale: Arc::from(default_locale(&config.locale, &catalogs.locales())),
1309 catalogs,
1310 app_name,
1311 brand_cache: Arc::new(RwLock::new(None)),
1312 field_types: Arc::new(field_types),
1313 column_types: Arc::new(column_types),
1314 plugin_defined,
1315 assets: Arc::new(assets),
1316 asset_urls: asset_urls_arc.clone(),
1317 pickers,
1318 overrides: Arc::new(field::NoOverrides),
1319 };
1320
1321 let mut protected = Router::new().route(&admin_path, get(dashboard));
1322 for resource in &resources {
1323 protected = protected.merge(mount_resource(
1324 resource,
1325 &state.field_types,
1326 &state.column_types,
1327 &permission_codes,
1328 &persisters,
1329 &app_listeners,
1330 ));
1331 }
1332 for reg in &app_screens {
1336 let base = format!("{admin_path}{}", reg.base_path);
1337 let ctx = routes::RouteCtx::new(
1338 state.db.clone(),
1339 &base,
1340 &admin_path,
1341 &state.origin,
1342 state.plugin_defined.clone(),
1343 );
1344 protected = protected.merge(guard_with_permission(
1345 Router::new().nest_service(&base, reg.screen.mount(&ctx)),
1346 ®.permission,
1347 ));
1348 }
1349
1350 protected = protected.merge(guard_with_permission(
1353 Router::new()
1354 .route(
1355 &format!("{admin_path}/roles/new"),
1356 get(roles::new_form).post(roles::create),
1357 )
1358 .route(
1359 &format!("{admin_path}/roles/{{id}}/edit"),
1360 get(roles::edit_form).post(roles::update),
1361 ),
1362 "backend.manage_roles",
1363 ));
1364 protected = protected.merge(guard_with_permission(
1367 Router::new()
1368 .route(
1369 &format!("{admin_path}/users/new"),
1370 get(users::new_form).post(users::create),
1371 )
1372 .route(
1373 &format!("{admin_path}/users/{{id}}/edit"),
1374 get(users::edit_form).post(users::update),
1375 )
1376 .route(
1377 &format!("{admin_path}/users/{{id}}/active"),
1378 post(users::set_active),
1379 )
1380 .route(
1381 &format!("{admin_path}/users/{{id}}/password"),
1382 post(users::reset_password),
1383 )
1384 .route(
1385 &format!("{admin_path}/users/{{id}}/unlock"),
1386 post(users::unlock),
1387 ),
1388 "backend.manage_users",
1389 ));
1390 protected = protected.merge(guard_with_permission(
1393 Router::new()
1394 .route(&format!("{admin_path}/plugins"), get(plugins::index))
1395 .route(
1396 &format!("{admin_path}/plugins/toggle"),
1397 post(plugins::toggle),
1398 ),
1399 plugins::MANAGE_PERMISSION,
1400 ));
1401 protected = protected
1402 .route(&format!("{admin_path}/settings"), get(settings_index))
1403 .route(
1404 &format!("{admin_path}/preferences"),
1405 get(preferences_form).post(preferences_update),
1406 )
1407 .route(
1408 &format!("{admin_path}/preferences/password"),
1409 post(password_update),
1410 )
1411 .route(
1412 &format!("{admin_path}/preferences/sessions/revoke"),
1413 post(session_revoke),
1414 )
1415 .route(
1416 &format!("{admin_path}/preferences/sessions/revoke-others"),
1417 post(session_revoke_others),
1418 )
1419 .route(
1422 &format!("{admin_path}/pickers/{{source}}/search"),
1423 any(picker::search),
1424 )
1425 .route(
1426 &format!("{admin_path}/pickers/{{source}}/resolve"),
1427 any(picker::resolve),
1428 )
1429 .route(&format!("{admin_path}/logout"), post(logout));
1430
1431 for item in settings.iter().filter(|i| i.link.is_none()) {
1435 let path = format!("{admin_path}{}", item.route());
1436 let code = item.code.clone();
1437 let edit_code = code.clone();
1438 protected = protected.route(
1439 &path,
1440 get(
1441 move |State(state): State<AdminState>,
1442 Extension(shell): Extension<Shell>,
1443 Extension(user): Extension<AuthenticatedUser>| {
1444 let code = edit_code.clone();
1445 async move { settings_edit(state, shell, user, code).await }
1446 },
1447 )
1448 .post(
1449 move |State(state): State<AdminState>,
1450 Extension(shell): Extension<Shell>,
1451 Extension(user): Extension<AuthenticatedUser>,
1452 Extension(session): Extension<session::SessionHandle>,
1453 Form(data): Form<HashMap<String, String>>| {
1454 let code = code.clone();
1455 async move { settings_update(state, shell, user, session, code, data).await }
1456 },
1457 ),
1458 );
1459 }
1460
1461 protected
1462 .route_layer(middleware::from_fn_with_state(state.clone(), require_auth))
1463 .route(
1467 &format!("{admin_path}/login"),
1468 get(login_form).post(login_submit),
1469 )
1470 .route(
1471 &format!("{admin_path}/setup"),
1472 get(setup_form).post(setup_submit),
1473 )
1474 .route(&format!("{admin_path}/assets/{{*path}}"), get(serve_asset))
1475 .merge(mount_public(
1479 &app_public,
1480 &state.db,
1481 &admin_path,
1482 &state.origin,
1483 &state.plugin_defined,
1484 ))
1485 .fallback(not_found_fallback)
1487 .layer(middleware::from_fn_with_state(
1490 state.clone(),
1491 enforce_origin,
1492 ))
1493 .layer(middleware::from_fn_with_state(
1496 state.clone(),
1497 capture_client,
1498 ))
1499 .layer(
1504 tower_http::set_header::SetResponseHeaderLayer::if_not_present(
1505 header::CACHE_CONTROL,
1506 axum::http::HeaderValue::from_static(http_cache::PRIVATE_NO_STORE),
1507 ),
1508 )
1509 .layer(
1513 tower_http::set_header::SetResponseHeaderLayer::if_not_present(
1514 header::VARY,
1515 axum::http::HeaderValue::from_static("HX-Request"),
1516 ),
1517 )
1518 .layer(tower_http::catch_panic::CatchPanicLayer::custom(
1519 handle_panic,
1520 ))
1521 .with_state(state)
1522}
1523
1524async fn not_found_fallback() -> AdminError {
1526 AdminError::NotFound
1527}
1528
1529fn handle_panic(err: Box<dyn std::any::Any + Send + 'static>) -> Response {
1531 let cause = err
1532 .downcast_ref::<&str>()
1533 .map(|s| s.to_string())
1534 .or_else(|| err.downcast_ref::<String>().cloned())
1535 .unwrap_or_else(|| "unknown panic".to_string());
1536 tracing::error!(panic = cause, "admin handler panicked");
1537 error::masked_500()
1538}
1539
1540pub fn normalize_path(path: &str) -> String {
1545 let trimmed = path.trim().trim_matches('/');
1546 if trimmed.is_empty() {
1547 "/admin".to_string()
1548 } else {
1549 format!("/{trimmed}")
1550 }
1551}
1552
1553fn mount_public(
1557 regs: &[routes::PublicRouteReg],
1558 db: &Db,
1559 admin_path: &str,
1560 origin: &str,
1561 plugin_defined: &Arc<laterite_core::Registry>,
1562) -> Router<AdminState> {
1563 let mut router = Router::new();
1564 for reg in regs {
1565 let ctx = routes::RouteCtx::new(
1566 db.clone(),
1567 ®.path,
1568 admin_path,
1569 origin,
1570 plugin_defined.clone(),
1571 );
1572 router = router.nest_service(
1577 ®.path,
1578 reg.route.mount(&ctx).fallback(not_found_fallback),
1579 );
1580 }
1581 router
1582}
1583
1584pub(crate) fn rebase_resource(base: &str, resource: &mut Resource) {
1587 let old = resource.base_path.clone();
1588 resource.base_path = base.to_string();
1589 if let Some(edit_base) = &mut resource.list.edit_base {
1590 if edit_base == &old {
1591 *edit_base = base.to_string();
1592 }
1593 }
1594 if let Some(form) = &mut resource.form {
1595 if form.base_path == old {
1596 form.base_path = base.to_string();
1597 }
1598 }
1599}
1600
1601fn prefix_resource(admin_path: &str, resource: &mut Resource) {
1602 resource.base_path = format!("{admin_path}{}", resource.base_path);
1603 if let Some(edit_base) = &mut resource.list.edit_base {
1604 *edit_base = format!("{admin_path}{edit_base}");
1605 }
1606 if let Some(form) = &mut resource.form {
1607 form.base_path = format!("{admin_path}{}", form.base_path);
1608 }
1609}
1610
1611pub(crate) struct AdminAsset {
1613 pub mime: &'static str,
1614 pub bytes: std::borrow::Cow<'static, [u8]>,
1618}
1619
1620pub(crate) type AssetRegistry = HashMap<&'static str, AdminAsset>;
1623
1624pub(crate) type AssetUrls = HashMap<&'static str, String>;
1628
1629pub(crate) fn asset_urls(registry: &AssetRegistry) -> AssetUrls {
1631 registry
1632 .iter()
1633 .map(|(&key, asset)| {
1634 (
1635 key,
1636 http_cache::fingerprint(key, &http_cache::digest(&asset.bytes)),
1637 )
1638 })
1639 .collect()
1640}
1641
1642pub(crate) fn page_assets(
1649 keys: &[&str],
1650 base: &str,
1651 registry: &AssetRegistry,
1652 urls: &AssetUrls,
1653) -> Vec<PageAsset> {
1654 let mut seen = std::collections::HashSet::new();
1655 let mut out = Vec::new();
1656 for &key in keys {
1657 if !seen.insert(key) {
1658 continue;
1659 }
1660 match (registry.get(key), urls.get(key)) {
1661 (Some(asset), Some(path)) => out.push(PageAsset {
1662 url: format!("{base}/assets/{path}"),
1663 css: asset.mime.contains("css"),
1664 }),
1665 _ => debug_assert!(false, "asset key `{key}` is not registered"),
1666 }
1667 }
1668 out
1669}
1670
1671pub(crate) fn builtin_assets() -> AssetRegistry {
1680 let font = |bytes: &'static [u8]| AdminAsset {
1681 mime: "font/woff2",
1682 bytes: std::borrow::Cow::Borrowed(bytes),
1683 };
1684 HashMap::from([
1685 (
1686 "laterite.css",
1687 AdminAsset {
1688 mime: "text/css; charset=utf-8",
1689 bytes: std::borrow::Cow::Borrowed(include_bytes!("../assets/laterite.css")),
1690 },
1691 ),
1692 (
1693 "laterite.js",
1694 AdminAsset {
1695 mime: "text/javascript; charset=utf-8",
1696 bytes: std::borrow::Cow::Borrowed(include_bytes!("../assets/laterite.js")),
1697 },
1698 ),
1699 (
1700 "vendor/htmx.min.js",
1701 AdminAsset {
1702 mime: "text/javascript; charset=utf-8",
1703 bytes: std::borrow::Cow::Borrowed(include_bytes!("../assets/vendor/htmx.min.js")),
1704 },
1705 ),
1706 (
1707 "fields/ref-picker.js",
1708 AdminAsset {
1709 mime: "text/javascript; charset=utf-8",
1710 bytes: std::borrow::Cow::Borrowed(include_bytes!("../assets/fields/ref-picker.js")),
1711 },
1712 ),
1713 (
1714 "fields/ref-picker.css",
1715 AdminAsset {
1716 mime: "text/css; charset=utf-8",
1717 bytes: std::borrow::Cow::Borrowed(include_bytes!(
1718 "../assets/fields/ref-picker.css"
1719 )),
1720 },
1721 ),
1722 (
1723 "mark.svg",
1724 AdminAsset {
1725 mime: "image/svg+xml",
1726 bytes: std::borrow::Cow::Borrowed(include_bytes!("../assets/mark.svg")),
1727 },
1728 ),
1729 (
1730 "mark.png",
1731 AdminAsset {
1732 mime: "image/png",
1733 bytes: std::borrow::Cow::Borrowed(include_bytes!("../assets/mark.png")),
1734 },
1735 ),
1736 (
1737 "fonts/space-grotesk-500.woff2",
1738 font(include_bytes!("../assets/fonts/space-grotesk-500.woff2")),
1739 ),
1740 (
1741 "fonts/space-grotesk-600.woff2",
1742 font(include_bytes!("../assets/fonts/space-grotesk-600.woff2")),
1743 ),
1744 (
1745 "fonts/space-grotesk-700.woff2",
1746 font(include_bytes!("../assets/fonts/space-grotesk-700.woff2")),
1747 ),
1748 (
1749 "fonts/ibm-plex-sans-400.woff2",
1750 font(include_bytes!("../assets/fonts/ibm-plex-sans-400.woff2")),
1751 ),
1752 (
1753 "fonts/ibm-plex-sans-600.woff2",
1754 font(include_bytes!("../assets/fonts/ibm-plex-sans-600.woff2")),
1755 ),
1756 (
1757 "fonts/ibm-plex-mono-400.woff2",
1758 font(include_bytes!("../assets/fonts/ibm-plex-mono-400.woff2")),
1759 ),
1760 (
1761 "fonts/ibm-plex-mono-600.woff2",
1762 font(include_bytes!("../assets/fonts/ibm-plex-mono-600.woff2")),
1763 ),
1764 ])
1765}
1766
1767async fn serve_asset(
1769 State(state): State<AdminState>,
1770 headers: HeaderMap,
1771 Path(path): Path<String>,
1772) -> Response {
1773 let (key, fingerprinted) = http_cache::strip_fingerprint(&path);
1777 let Some(asset) = state.assets.get(key.as_str()) else {
1778 return not_found();
1779 };
1780 let policy = if fingerprinted {
1781 http_cache::IMMUTABLE
1782 } else {
1783 http_cache::REVALIDATE
1784 };
1785 http_cache::conditional(&headers, asset.mime, policy, asset.bytes.to_vec())
1786}
1787
1788fn mount_resource(
1793 resource: &Resource,
1794 field_types: &field::FieldRegistry,
1795 column_types: &list::ColumnRegistry,
1796 permission_codes: &std::collections::HashSet<String>,
1797 persisters: &persist::PersisterRegistry,
1798 listeners: &[laterite_core::ModelListenerReg],
1799) -> Router<AdminState> {
1800 list::check(&resource.list, column_types, permission_codes)
1804 .unwrap_or_else(|e| panic!("admin resource `{}`: {e}", resource.base_path));
1805 if resource.form.is_some() && resource.permission.is_none() {
1810 panic!(
1811 "admin resource `{}` has a create/edit form but no permission; a write \
1812 resource must declare a permission",
1813 resource.base_path
1814 );
1815 }
1816 let base = resource.base_path.clone();
1817 let list_path = base.clone();
1818 let list_cfg = resource.list.clone();
1819 let mut router = Router::new().route(
1820 &base,
1821 get(
1822 move |State(state): State<AdminState>,
1823 Extension(shell): Extension<Shell>,
1824 Query(params): Query<list::ListParams>,
1825 Query(raw): Query<std::collections::HashMap<String, String>>,
1826 Extension(user): Extension<AuthenticatedUser>,
1827 headers: axum::http::HeaderMap| {
1828 let cfg = list_cfg.clone();
1829 let path = list_path.clone();
1830 async move {
1831 list::handle(&state, &cfg, &path, params, &raw, &user, shell, &headers).await
1832 }
1833 },
1834 ),
1835 );
1836
1837 let (export_cfg, export_path) = (resource.list.clone(), resource.base_path.clone());
1840 if resource.list.exportable {
1841 router = router.route(
1842 &format!("{base}/export"),
1843 get(
1844 move |state: State<AdminState>,
1845 Query(raw): Query<std::collections::HashMap<String, String>>,
1846 Extension(user): Extension<AuthenticatedUser>,
1847 Extension(shell): Extension<Shell>,
1848 Extension(session): Extension<session::SessionHandle>| {
1849 let cfg = export_cfg.clone();
1850 let path = export_path.clone();
1851 async move {
1852 export::handle(state, &cfg, &path, &raw, &user, &shell, &session).await
1853 }
1854 },
1855 ),
1856 );
1857 }
1858
1859 let (columns_cfg, columns_path) = (resource.list.clone(), resource.base_path.clone());
1860 router = router.route(
1861 &format!("{base}/columns"),
1862 post(
1863 move |State(state): State<AdminState>,
1864 Extension(user): Extension<AuthenticatedUser>,
1865 Extension(session): Extension<session::SessionHandle>,
1866 headers: axum::http::HeaderMap,
1867 Form(pairs): Form<Vec<(String, String)>>| {
1868 let cfg = columns_cfg.clone();
1869 let path = columns_path.clone();
1870 async move {
1871 list::set_columns(&state, &cfg, &path, &user, &session, &headers, &pairs).await
1872 }
1873 },
1874 ),
1875 );
1876
1877 if resource.list.deletable {
1878 let persister: Arc<dyn persist::Persister> =
1882 match resource.form.as_ref().and_then(|f| f.persist.as_ref()) {
1883 Some(key) => persisters.get(key).cloned().unwrap_or_else(|| {
1884 panic!(
1885 "admin resource `{}`: unregistered persister `{key}`",
1886 resource.base_path
1887 )
1888 }),
1889 None => Arc::new(persist::DefaultPersister::from_list(&resource.list)),
1890 };
1891 let ctx = Arc::new(bulk::BulkContext {
1892 base_path: resource.base_path.clone(),
1893 entity: resource.list.entity.clone(),
1894 persister,
1895 listeners: listeners
1896 .iter()
1897 .filter(|reg| reg.matches(&resource.list.entity))
1898 .map(|reg| reg.listener.clone())
1899 .collect(),
1900 });
1901 router =
1902 router.route(
1903 &format!("{base}/delete"),
1904 post(
1905 move |state: State<AdminState>,
1906 user: Extension<AuthenticatedUser>,
1907 session: Extension<session::SessionHandle>,
1908 headers: axum::http::HeaderMap,
1909 form: Form<Vec<(String, String)>>| {
1910 let ctx = ctx.clone();
1911 async move {
1912 bulk::delete_handler(state, user, session, ctx, headers, form).await
1913 }
1914 },
1915 ),
1916 );
1917 }
1918
1919 if let Some(form_cfg) = resource.form.clone() {
1920 let prepared = Arc::new(
1923 form::PreparedForm::prepare(form_cfg, field_types, persisters, listeners)
1924 .unwrap_or_else(|e| panic!("admin resource `{}`: {e}", resource.base_path)),
1925 );
1926 let (new_pf, create_pf) = (prepared.clone(), prepared.clone());
1927 router = router.route(
1928 &format!("{base}/new"),
1929 get(
1930 move |State(state): State<AdminState>, Extension(shell): Extension<Shell>| {
1931 let pf = new_pf.clone();
1932 async move { form::new_form(&state, &pf, shell) }
1933 },
1934 )
1935 .post(
1936 move |State(state): State<AdminState>,
1937 Extension(shell): Extension<Shell>,
1938 Extension(user): Extension<AuthenticatedUser>,
1939 Extension(session): Extension<session::SessionHandle>,
1940 headers: axum::http::HeaderMap,
1941 Form(data): Form<HashMap<String, String>>| {
1942 let pf = create_pf.clone();
1943 async move {
1944 form::create(&state, &pf, data, shell, &user, &session, &headers).await
1945 }
1946 },
1947 ),
1948 );
1949
1950 let (edit_pf, update_pf) = (prepared.clone(), prepared.clone());
1951 router = router.route(
1952 &format!("{base}/{{id}}/edit"),
1953 get(
1954 move |State(state): State<AdminState>,
1955 Extension(shell): Extension<Shell>,
1956 Path(id): Path<String>| {
1957 let pf = edit_pf.clone();
1958 async move { form::edit_form(&state, &pf, id, shell).await }
1959 },
1960 )
1961 .post(
1962 move |State(state): State<AdminState>,
1963 Extension(shell): Extension<Shell>,
1964 Extension(user): Extension<AuthenticatedUser>,
1965 Extension(session): Extension<session::SessionHandle>,
1966 Path(id): Path<String>,
1967 headers: axum::http::HeaderMap,
1968 Form(data): Form<HashMap<String, String>>| {
1969 let pf = update_pf.clone();
1970 async move {
1971 form::update(&state, &pf, id, data, shell, &user, &session, &headers).await
1972 }
1973 },
1974 ),
1975 );
1976 }
1977
1978 if let Some(permission) = &resource.permission {
1980 router = guard_with_permission(router, permission);
1981 }
1982 router
1983}
1984
1985fn guard_with_permission(router: Router<AdminState>, permission: &str) -> Router<AdminState> {
1990 let needed: Arc<str> = Arc::from(permission);
1991 router.route_layer(middleware::from_fn(
1992 move |Extension(user): Extension<AuthenticatedUser>, req: Request, next: Next| {
1993 let needed = needed.clone();
1994 async move {
1995 if user.allows(&needed) {
1996 next.run(req).await
1997 } else {
1998 forbidden()
1999 }
2000 }
2001 },
2002 ))
2003}
2004
2005async fn require_auth(
2011 State(state): State<AdminState>,
2012 jar: CookieJar,
2013 request: Request,
2014 next: Next,
2015) -> Response {
2016 let login = format!("{}/login", state.admin_path);
2017 let client_ctx = request
2018 .extensions()
2019 .get::<RequestContext>()
2020 .cloned()
2021 .unwrap_or_default();
2022 let mut ended: Option<laterite_auth::SessionEnd> = None;
2027 let live = match jar.get(SESSION_COOKIE) {
2028 Some(cookie) => {
2029 let token = cookie.value().to_string();
2030 match state.auth.resolve_session(&token).await {
2031 Ok(resolved) => Some((token, resolved)),
2032 Err(_) => {
2033 ended = state.auth.session_end(&token).await.ok().flatten();
2034 None
2035 }
2036 }
2037 }
2038 None => None,
2039 };
2040 let htmx = request.headers().contains_key("hx-request");
2041 let (token, resolved, recalled) = match live {
2042 Some((token, resolved)) => (token, resolved, None),
2043 None if matches!(ended, Some(laterite_auth::SessionEnd::Revoked(_))) => {
2046 return signed_out(&state, jar, &login, ended, htmx);
2047 }
2048 None => match recall(&state, &jar, &client_ctx).await {
2049 Some((token, resolved, credential)) => (token, resolved, Some(credential)),
2050 None => {
2051 if let Some(cookie) = jar.get(REMEMBER_COOKIE) {
2055 if let Ok(Some(reason)) = state.auth.remember_end(cookie.value()).await {
2056 ended = Some(laterite_auth::SessionEnd::Revoked(reason));
2057 }
2058 }
2059 return signed_out(&state, jar, &login, ended, htmx);
2060 }
2061 },
2062 };
2063 let handle = session::SessionHandle::from_blob(resolved.data.as_deref());
2064
2065 let mut request = request;
2070 let safe = session::is_safe_method(request.method());
2071 let mut deferred: Option<session::CsrfPending> = None;
2073 if !safe {
2074 let (parts, body) = request.into_parts();
2075 let (body, submitted) = if session::is_multipart(&parts.headers) {
2082 let token = session::header_token(&parts.headers)
2083 .or_else(|| session::query_token(parts.uri.query()));
2084 if token.is_none() {
2089 deferred = Some(session::CsrfPending::default());
2090 }
2091 (body, token)
2092 } else {
2093 let bytes = axum::body::to_bytes(body, MAX_FORM_BYTES)
2094 .await
2095 .unwrap_or_default();
2096 let token = session::submitted_token(&parts.headers, &bytes);
2097 (Body::from(bytes), token)
2098 };
2099 if deferred.is_none() && !session::token_matches(&handle.csrf_token(), submitted.as_deref())
2100 {
2101 tracing::warn!(
2102 user_id = resolved.identity.user.id,
2103 "admin CSRF check failed"
2104 );
2105 return error::csrf_rejected();
2106 }
2107 request = Request::from_parts(parts, body);
2108 }
2109
2110 let user = resolved.identity;
2111 let acting_user_id = user.user.id;
2113 let path = request.uri().path().to_string();
2114 let preferences = format!("{}/preferences", state.admin_path);
2117 if !path.starts_with(&preferences)
2118 && path != format!("{}/logout", state.admin_path)
2119 && state
2120 .auth
2121 .must_change_password(user.user.id)
2122 .await
2123 .unwrap_or(false)
2124 {
2125 let to = format!("{preferences}#password");
2126 let response = if htmx {
2127 (
2128 [("HX-Redirect", to.as_str())],
2129 axum::http::StatusCode::NO_CONTENT,
2130 )
2131 .into_response()
2132 } else {
2133 Redirect::to(&to).into_response()
2134 };
2135 return with_recall_cookies(response, recalled, jar, token, &state);
2136 }
2137 let flash = if safe {
2140 handle.take_flash()
2141 } else {
2142 Vec::new()
2143 };
2144 let accept_language = request
2148 .headers()
2149 .get("accept-language")
2150 .and_then(|v| v.to_str().ok());
2151 let serveable = state.catalogs.locales();
2152 let chain = resolve_locale_chain(
2153 user.user.locale.as_deref(),
2154 accept_language,
2155 &state.default_locale,
2156 &serveable,
2157 );
2158 let i18n = Translator::with_chain(chain, state.catalogs.clone());
2159 let translator = i18n.clone();
2162 let (sidebar, active_nav) = resolve_nav_context(
2163 &state.nav,
2164 &state.settings,
2165 &state.admin_path,
2166 &user.permissions,
2167 &path,
2168 &i18n,
2169 icons::Icons::new(&state.icons, &state.sprite_url),
2170 );
2171 let brand = state.brand().await;
2172 let shell = Shell::new(
2173 &state.admin_path,
2174 brand,
2175 &state.nav,
2176 &user,
2177 state.timezone,
2178 sidebar,
2179 active_nav.as_deref(),
2180 handle.csrf_token(),
2181 flash,
2182 i18n,
2183 state.asset_urls.clone(),
2184 state.origin.to_string(),
2185 state.icons.clone(),
2186 state.sprite_url.clone(),
2187 );
2188 request.extensions_mut().insert(user);
2189 request.extensions_mut().insert(shell);
2190 request.extensions_mut().insert(handle.clone());
2191 if let Some(pending) = &deferred {
2193 request.extensions_mut().insert(pending.clone());
2194 }
2195 let mut response = next.run(request).await;
2196
2197 if let Some(pending) = &deferred {
2202 if !pending.was_satisfied() {
2203 tracing::error!(
2204 user_id = acting_user_id,
2205 "a multipart route returned without verifying its request token"
2206 );
2207 return error::csrf_rejected();
2208 }
2209 }
2210
2211 if let Some(meta) = response.extensions().get::<error::ErrorMeta>().copied() {
2215 response = error::localized_error(meta.kind, &translator);
2216 }
2217
2218 if let Some(blob) = handle.dirty_blob() {
2221 if let Err(e) = state.auth.set_session_data(&token, &blob).await {
2222 tracing::error!(error = %e, "persisting admin session failed");
2223 }
2224 }
2225 with_recall_cookies(response, recalled, jar, token, &state)
2226}
2227
2228fn with_recall_cookies(
2232 response: Response,
2233 recalled: Option<laterite_auth::RememberCredential>,
2234 jar: CookieJar,
2235 token: String,
2236 state: &AdminState,
2237) -> Response {
2238 match recalled {
2239 Some(credential) => {
2240 let jar = jar
2241 .add(session_cookie(
2242 token,
2243 &state.admin_path,
2244 state.secure_cookie,
2245 ))
2246 .add(remember_cookie(
2247 credential,
2248 &state.admin_path,
2249 state.secure_cookie,
2250 ));
2251 (jar, response).into_response()
2252 }
2253 None => response,
2254 }
2255}
2256
2257async fn recall(
2261 state: &AdminState,
2262 jar: &CookieJar,
2263 ctx: &RequestContext,
2264) -> Option<(
2265 String,
2266 laterite_auth::ResolvedSession,
2267 laterite_auth::RememberCredential,
2268)> {
2269 let presented = jar.get(REMEMBER_COOKIE)?.value().to_string();
2270 let recalled = state.auth.consume_remember(&presented, ctx).await.ok()?;
2271 let token = recalled.session.token.clone();
2272 let resolved = state.auth.resolve_session(&token).await.ok()?;
2273 Some((token, resolved, recalled.remember))
2274}
2275
2276const MAX_FORM_BYTES: usize = 1024 * 1024;
2279
2280async fn capture_client(
2288 State(state): State<AdminState>,
2289 mut request: Request,
2290 next: Next,
2291) -> Response {
2292 let peer = request
2293 .extensions()
2294 .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
2295 .map(|info| info.0);
2296 let headers = request.headers();
2297 let ctx = RequestContext {
2298 ip_address: clientip::client_ip(peer, headers, &state.trusted_proxies),
2299 user_agent: clientip::user_agent(headers),
2300 };
2301 request.extensions_mut().insert(ctx);
2302 next.run(request).await
2303}
2304
2305async fn enforce_origin(State(state): State<AdminState>, request: Request, next: Next) -> Response {
2306 if !session::is_safe_method(request.method())
2307 && !session::origin_ok(request.headers(), &state.origin)
2308 {
2309 tracing::warn!(
2310 path = request.uri().path(),
2311 "admin CSRF origin check failed"
2312 );
2313 return error::csrf_rejected();
2314 }
2315 next.run(request).await
2316}
2317
2318#[derive(Deserialize)]
2319struct LoginQuery {
2320 ended: Option<String>,
2321}
2322
2323async fn login_form(
2324 State(state): State<AdminState>,
2325 headers: HeaderMap,
2326 Query(query): Query<LoginQuery>,
2327) -> Response {
2328 match state.auth.has_any_operator().await {
2330 Ok(false) => Redirect::to(&format!("{}/setup", state.admin_path)).into_response(),
2331 Ok(true) => {
2332 let i18n = pre_auth_translator(&state, &headers);
2333 let notice = query
2334 .ended
2335 .as_deref()
2336 .and_then(end_notice)
2337 .map(|text| i18n.t(&text));
2338 render(LoginTemplate {
2339 base: state.admin_path.to_string(),
2340 asset_urls: state.asset_urls.clone(),
2341 brand: state.brand().await,
2342 error: None,
2343 notice,
2344 i18n,
2345 })
2346 }
2347 Err(_) => render_error(),
2348 }
2349}
2350
2351#[derive(Deserialize)]
2352struct LoginForm {
2353 username: String,
2354 password: String,
2355 #[serde(default)]
2357 remember: Option<String>,
2358}
2359
2360async fn login_submit(
2361 State(state): State<AdminState>,
2362 jar: CookieJar,
2363 headers: HeaderMap,
2364 Extension(ctx): Extension<RequestContext>,
2365 Form(form): Form<LoginForm>,
2366) -> Response {
2367 match state
2368 .auth
2369 .authenticate(&form.username, &form.password, &ctx)
2370 .await
2371 {
2372 Ok(session) => {
2373 let wants_remember = form.remember.is_some();
2374 let user_id = session.user_id;
2375 let mut jar = jar.add(session_cookie(
2376 session.token,
2377 &state.admin_path,
2378 state.secure_cookie,
2379 ));
2380 if wants_remember {
2381 match state.auth.issue_remember(user_id).await {
2382 Ok(credential) => {
2383 jar = jar.add(remember_cookie(
2384 credential,
2385 &state.admin_path,
2386 state.secure_cookie,
2387 ));
2388 }
2389 Err(e) => {
2391 tracing::error!(error = %e, "issuing a stay-signed-in credential failed")
2392 }
2393 }
2394 }
2395 (jar, Redirect::to(&state.admin_path)).into_response()
2396 }
2397 Err(_) => {
2398 let i18n = pre_auth_translator(&state, &headers);
2399 render(LoginTemplate {
2400 base: state.admin_path.to_string(),
2401 asset_urls: state.asset_urls.clone(),
2402 brand: state.brand().await,
2403 error: Some(i18n.t(&t!("Invalid username or password."))),
2404 notice: None,
2405 i18n,
2406 })
2407 }
2408 }
2409}
2410
2411fn session_cookie(token: String, admin_path: &str, secure: bool) -> Cookie<'static> {
2420 Cookie::build((SESSION_COOKIE, token))
2421 .path(admin_path.to_string())
2422 .http_only(true)
2423 .secure(secure)
2424 .same_site(SameSite::Lax)
2425 .build()
2426}
2427
2428fn remember_cookie(
2431 credential: laterite_auth::RememberCredential,
2432 admin_path: &str,
2433 secure: bool,
2434) -> Cookie<'static> {
2435 let seconds = (credential.expires_at - chrono::Utc::now())
2436 .num_seconds()
2437 .max(0);
2438 Cookie::build((REMEMBER_COOKIE, credential.cookie))
2439 .path(admin_path.to_string())
2440 .http_only(true)
2441 .secure(secure)
2442 .same_site(SameSite::Lax)
2443 .max_age(cookie::time::Duration::seconds(seconds))
2444 .build()
2445}
2446
2447fn signed_out(
2454 state: &AdminState,
2455 jar: CookieJar,
2456 login: &str,
2457 ended: Option<laterite_auth::SessionEnd>,
2458 htmx: bool,
2459) -> Response {
2460 let to = match ended.map(laterite_auth::SessionEnd::code) {
2461 Some(code) => format!("{login}?ended={code}"),
2462 None => login.to_string(),
2463 };
2464 let jar = jar
2465 .remove(
2466 Cookie::build((SESSION_COOKIE, ""))
2467 .path(state.admin_path.to_string())
2468 .build(),
2469 )
2470 .remove(remember_removal(&state.admin_path));
2471 if htmx {
2472 let mut response = (jar, axum::http::StatusCode::NO_CONTENT).into_response();
2473 if let Ok(value) = axum::http::HeaderValue::from_str(&to) {
2474 response.headers_mut().insert("hx-redirect", value);
2475 }
2476 return response;
2477 }
2478 (jar, Redirect::to(&to)).into_response()
2479}
2480
2481fn end_notice(code: &str) -> Option<Text> {
2484 Some(match code {
2485 "password_changed" => {
2486 t!("Your password was changed, so you were signed out. Sign in with the new one.")
2487 }
2488 "deactivated" => t!("This account was deactivated."),
2489 "signed_out_elsewhere" => t!("You were signed out from another device."),
2490 "expired" => t!("Your session ended after a period of inactivity. Sign in again."),
2491 _ => return None,
2492 })
2493}
2494
2495fn remember_removal(admin_path: &str) -> Cookie<'static> {
2497 Cookie::build((REMEMBER_COOKIE, ""))
2498 .path(admin_path.to_string())
2499 .build()
2500}
2501
2502#[derive(Deserialize)]
2503struct SetupForm {
2504 username: String,
2505 first_name: String,
2506 last_name: String,
2507 email: String,
2508 password: String,
2509 timezone: String,
2510}
2511
2512async fn setup_form(State(state): State<AdminState>, headers: HeaderMap) -> Response {
2515 match state.auth.has_any_operator().await {
2516 Ok(true) => Redirect::to(&format!("{}/login", state.admin_path)).into_response(),
2517 Ok(false) => render(setup_view(
2518 &state.admin_path,
2519 state.brand().await,
2520 state.timezone,
2521 None,
2522 pre_auth_translator(&state, &headers),
2523 state.asset_urls.clone(),
2524 state.auth.password_policy().min_length,
2525 )),
2526 Err(_) => render_error(),
2527 }
2528}
2529
2530async fn setup_submit(
2531 State(state): State<AdminState>,
2532 jar: CookieJar,
2533 headers: HeaderMap,
2534 Form(form): Form<SetupForm>,
2535) -> Response {
2536 match state.auth.has_any_operator().await {
2538 Ok(true) => return Redirect::to(&format!("{}/login", state.admin_path)).into_response(),
2539 Ok(false) => {}
2540 Err(_) => return render_error(),
2541 }
2542
2543 let username = form.username.trim();
2544 let email = form.email.trim();
2545 let first_name = form.first_name.trim();
2546 let last_name = form.last_name.trim();
2547 let tz = form.timezone.trim();
2548 if username.is_empty() || email.is_empty() || first_name.is_empty() || form.password.is_empty()
2549 {
2550 return render(setup_view(
2551 &state.admin_path,
2552 state.brand().await,
2553 state.timezone,
2554 Some(t!(
2555 "Username, first name, email, and password are all required."
2556 )),
2557 pre_auth_translator(&state, &headers),
2558 state.asset_urls.clone(),
2559 state.auth.password_policy().min_length,
2560 ));
2561 }
2562 if tz.parse::<Tz>().is_err() {
2564 return render(setup_view(
2565 &state.admin_path,
2566 state.brand().await,
2567 state.timezone,
2568 Some(t!("That is not a recognised timezone.")),
2569 pre_auth_translator(&state, &headers),
2570 state.asset_urls.clone(),
2571 state.auth.password_policy().min_length,
2572 ));
2573 }
2574
2575 let min_length = state.auth.password_policy().min_length;
2576 if form.password.chars().count() < min_length {
2577 return render(setup_view(
2578 &state.admin_path,
2579 state.brand().await,
2580 state.timezone,
2581 Some(t!(
2582 "A password needs at least {n} characters.",
2583 n = min_length as i64
2584 )),
2585 pre_auth_translator(&state, &headers),
2586 state.asset_urls.clone(),
2587 state.auth.password_policy().min_length,
2588 ));
2589 }
2590 let new = NewOperator {
2591 username,
2592 email,
2593 first_name,
2594 last_name: (!last_name.is_empty()).then_some(last_name),
2595 password: &form.password,
2596 timezone: Some(tz),
2597 };
2598 let id = match state.auth.create_superuser(new).await {
2599 Ok(id) => id,
2600 Err(_) => {
2601 return render(setup_view(
2602 &state.admin_path,
2603 state.brand().await,
2604 state.timezone,
2605 Some(t!(
2606 "Could not create the account. The username or email may already be taken."
2607 )),
2608 pre_auth_translator(&state, &headers),
2609 state.asset_urls.clone(),
2610 state.auth.password_policy().min_length,
2611 ));
2612 }
2613 };
2614 let actor = laterite_core::Actor::system("first-run setup");
2617 let target = id.to_string();
2618 let entry = laterite_auth::AuditEntry::new(&actor, "backend.user.create").target(
2619 "backend_user",
2620 &target,
2621 Some(username),
2622 );
2623 if let Err(e) = state.auth.record_audit(entry).await {
2624 tracing::error!(error = %e, "failed to write audit log entry");
2625 }
2626
2627 match state
2629 .auth
2630 .authenticate(username, &form.password, &RequestContext::default())
2631 .await
2632 {
2633 Ok(session) => {
2634 let cookie = session_cookie(session.token, &state.admin_path, state.secure_cookie);
2635 (jar.add(cookie), Redirect::to(&state.admin_path)).into_response()
2636 }
2637 Err(_) => Redirect::to(&format!("{}/login", state.admin_path)).into_response(),
2638 }
2639}
2640
2641fn setup_view(
2644 admin_path: &str,
2645 brand: String,
2646 default_tz: Tz,
2647 error: Option<Text>,
2648 i18n: Translator,
2649 asset_urls: Arc<AssetUrls>,
2650 min_password: usize,
2651) -> SetupTemplate {
2652 let default_name = default_tz.name();
2653 let zones = TZ_VARIANTS
2654 .iter()
2655 .filter(|tz| zone_offered(tz.name()))
2656 .map(|tz| TzOption {
2657 name: tz.name().to_string(),
2658 selected: tz.name() == default_name,
2659 })
2660 .collect();
2661 SetupTemplate {
2662 base: admin_path.to_string(),
2663 asset_urls,
2664 brand,
2665 zones,
2666 error: error.map(|e| i18n.t(&e)),
2667 min_password: min_password as i64,
2668 i18n,
2669 }
2670}
2671
2672async fn logout(State(state): State<AdminState>, jar: CookieJar) -> Response {
2673 if let Some(cookie) = jar.get(SESSION_COOKIE) {
2674 let _ = state.auth.logout(cookie.value()).await;
2675 }
2676 if let Some(cookie) = jar.get(REMEMBER_COOKIE) {
2679 let _ = state.auth.revoke_remember(cookie.value()).await;
2680 }
2681 let removal = Cookie::build((SESSION_COOKIE, ""))
2682 .path(state.admin_path.to_string())
2683 .build();
2684 (
2685 jar.remove(removal)
2686 .remove(remember_removal(&state.admin_path)),
2687 Redirect::to(&format!("{}/login", state.admin_path)),
2688 )
2689 .into_response()
2690}
2691
2692async fn dashboard(
2693 Extension(shell): Extension<Shell>,
2694 Extension(user): Extension<AuthenticatedUser>,
2695) -> Response {
2696 render(DashboardTemplate {
2697 username: user.user.username,
2698 shell,
2699 })
2700}
2701
2702fn operator_can_see(item: &settings::SettingsItem, perms: &PermissionSet) -> bool {
2705 match &item.permission {
2706 None => true,
2707 Some(p) => perms.allows(p),
2708 }
2709}
2710
2711fn visible_settings(
2715 items: &[settings::SettingsItem],
2716 perms: &PermissionSet,
2717) -> Vec<settings::SettingsItem> {
2718 items
2719 .iter()
2720 .filter(|item| operator_can_see(item, perms))
2721 .cloned()
2722 .collect()
2723}
2724
2725async fn settings_index(Extension(shell): Extension<Shell>) -> Response {
2726 settings::index(shell)
2727}
2728
2729async fn settings_edit(
2730 state: AdminState,
2731 shell: Shell,
2732 user: AuthenticatedUser,
2733 code: String,
2734) -> Response {
2735 let items = visible_settings(&state.settings, &user.permissions);
2738 match items
2739 .iter()
2740 .find(|item| item.code == code && item.link.is_none())
2741 {
2742 Some(item) => settings::edit_form(&state, item, shell).await,
2743 None => not_found(),
2744 }
2745}
2746
2747async fn settings_update(
2748 state: AdminState,
2749 shell: Shell,
2750 user: AuthenticatedUser,
2751 session: session::SessionHandle,
2752 code: String,
2753 data: HashMap<String, String>,
2754) -> Response {
2755 let items = visible_settings(&state.settings, &user.permissions);
2756 match items
2757 .iter()
2758 .find(|item| item.code == code && item.link.is_none())
2759 {
2760 Some(item) => settings::update(&state, item, data, shell, &session, &user).await,
2761 None => not_found(),
2762 }
2763}
2764
2765async fn preferences_form(
2767 State(state): State<AdminState>,
2768 Extension(shell): Extension<Shell>,
2769 Extension(user): Extension<AuthenticatedUser>,
2770 jar: CookieJar,
2771) -> Response {
2772 let account = account_security(&state, &user, &shell, &jar).await;
2773 render(preferences_view(
2774 &shell,
2775 &user,
2776 state.timezone,
2777 &state.default_locale,
2778 &offered_locales(&state.catalogs),
2779 account,
2780 state.auth.password_policy().min_length,
2781 ))
2782}
2783
2784#[derive(Deserialize)]
2785struct RevokeSessionForm {
2786 id: String,
2787}
2788
2789async fn session_revoke(
2791 State(state): State<AdminState>,
2792 Extension(user): Extension<AuthenticatedUser>,
2793 Extension(session): Extension<session::SessionHandle>,
2794 Form(form): Form<RevokeSessionForm>,
2795) -> Response {
2796 match state.auth.revoke_session(user.user.id, &form.id).await {
2797 Ok(true) => session.push_flash(FlashLevel::Success, t!("That session was signed out.")),
2798 Ok(false) => session.push_flash(FlashLevel::Info, t!("That session had already ended.")),
2799 Err(e) => {
2800 tracing::error!(error = %e, "revoking a session failed");
2801 session.push_flash(
2802 FlashLevel::Error,
2803 t!("That session could not be signed out."),
2804 );
2805 }
2806 }
2807 Redirect::to(&format!("{}/preferences", state.admin_path)).into_response()
2808}
2809
2810async fn session_revoke_others(
2812 State(state): State<AdminState>,
2813 Extension(user): Extension<AuthenticatedUser>,
2814 Extension(session): Extension<session::SessionHandle>,
2815 jar: CookieJar,
2816) -> Response {
2817 let token = jar
2818 .get(SESSION_COOKIE)
2819 .map(|c| c.value().to_string())
2820 .unwrap_or_default();
2821 match state.auth.sign_out_everywhere(user.user.id, &token).await {
2822 Ok(_) => session.push_flash(
2823 FlashLevel::Success,
2824 t!("Every other session was signed out."),
2825 ),
2826 Err(e) => {
2827 tracing::error!(error = %e, "signing out other sessions failed");
2828 session.push_flash(
2829 FlashLevel::Error,
2830 t!("Those sessions could not be signed out."),
2831 );
2832 }
2833 }
2834 (
2837 jar.remove(remember_removal(&state.admin_path)),
2838 Redirect::to(&format!("{}/preferences", state.admin_path)),
2839 )
2840 .into_response()
2841}
2842
2843#[derive(Deserialize)]
2844struct PasswordForm {
2845 current_password: String,
2846 new_password: String,
2847 confirm_password: String,
2848}
2849
2850async fn password_update(
2855 State(state): State<AdminState>,
2856 Extension(user): Extension<AuthenticatedUser>,
2857 Extension(session): Extension<session::SessionHandle>,
2858 Extension(ctx): Extension<RequestContext>,
2859 jar: CookieJar,
2860 Form(form): Form<PasswordForm>,
2861) -> Response {
2862 let back = format!("{}/preferences#password", state.admin_path);
2863 let refuse = |message: Text| {
2864 session.push_flash(FlashLevel::Error, message);
2865 Redirect::to(&back).into_response()
2866 };
2867 if form.new_password != form.confirm_password {
2868 return refuse(t!("The new passwords do not match."));
2869 }
2870 let min_length = state.auth.password_policy().min_length;
2871 if form.new_password.chars().count() < min_length {
2872 return refuse(t!(
2873 "A password needs at least {n} characters.",
2874 n = min_length as i64
2875 ));
2876 }
2877 let remembered_here = match jar.get(REMEMBER_COOKIE) {
2880 Some(cookie) => {
2881 state
2882 .auth
2883 .remember_holder(cookie.value())
2884 .await
2885 .ok()
2886 .flatten()
2887 == Some(user.user.id)
2888 }
2889 None => false,
2890 };
2891 let token = jar
2892 .get(SESSION_COOKIE)
2893 .map(|c| c.value().to_string())
2894 .unwrap_or_default();
2895 let changed = state
2896 .auth
2897 .change_own_password(
2898 user.user.id,
2899 &form.current_password,
2900 &form.new_password,
2901 &token,
2902 &ctx,
2903 )
2904 .await;
2905 match changed {
2906 Ok(()) => {}
2907 Err(laterite_auth::AuthError::InvalidCredentials) => {
2908 return refuse(t!("Your current password is not correct."));
2909 }
2910 Err(laterite_auth::AuthError::TooManyAttempts) => {
2911 return refuse(t!("Too many attempts. Try again later."));
2912 }
2913 Err(e) => {
2914 tracing::error!(error = %e, "changing a password failed");
2915 return refuse(t!("The password could not be changed."));
2916 }
2917 }
2918 session.push_flash_sticky(
2919 FlashLevel::Success,
2920 t!("Password changed. Every other device was signed out."),
2921 );
2922 let jar = if remembered_here {
2923 match state.auth.issue_remember(user.user.id).await {
2924 Ok(credential) => jar.add(remember_cookie(
2925 credential,
2926 &state.admin_path,
2927 state.secure_cookie,
2928 )),
2929 Err(e) => {
2930 tracing::error!(error = %e, "reissuing a stay-signed-in credential failed");
2931 jar.remove(remember_removal(&state.admin_path))
2932 }
2933 }
2934 } else if jar.get(REMEMBER_COOKIE).is_some() {
2935 jar.remove(remember_removal(&state.admin_path))
2938 } else {
2939 jar
2940 };
2941 (
2942 jar,
2943 Redirect::to(&format!("{}/preferences", state.admin_path)),
2944 )
2945 .into_response()
2946}
2947
2948#[derive(Deserialize)]
2949struct PreferencesForm {
2950 timezone: String,
2951 #[serde(default)]
2953 locale: String,
2954}
2955
2956async fn preferences_update(
2957 State(state): State<AdminState>,
2958 Extension(user): Extension<AuthenticatedUser>,
2959 Extension(session): Extension<session::SessionHandle>,
2960 Form(form): Form<PreferencesForm>,
2961) -> Response {
2962 let back = format!("{}/preferences", state.admin_path);
2963 let offered = offered_locales(&state.catalogs);
2964 let tz = form.timezone.trim();
2966 let tz_stored = if tz.is_empty() {
2967 None
2968 } else if tz.parse::<Tz>().is_ok() {
2969 Some(tz)
2970 } else {
2971 session.push_flash(FlashLevel::Error, t!("That is not a recognised timezone."));
2972 return Redirect::to(&back).into_response();
2973 };
2974 let loc = form.locale.trim();
2975 let loc_stored = if loc.is_empty() {
2976 None
2977 } else if offered.iter().any(|l| l == loc) {
2978 Some(loc)
2979 } else {
2980 session.push_flash(FlashLevel::Error, t!("That is not a supported language."));
2981 return Redirect::to(&back).into_response();
2982 };
2983 if state
2984 .auth
2985 .set_user_timezone(user.user.id, tz_stored)
2986 .await
2987 .is_err()
2988 {
2989 return render_error();
2990 }
2991 match state.auth.set_user_locale(user.user.id, loc_stored).await {
2992 Ok(()) => {
2993 session.push_flash(session::FlashLevel::Success, t!("Preferences saved."));
2994 Redirect::to(&back).into_response()
2995 }
2996 Err(_) => render_error(),
2997 }
2998}
2999
3000fn preferences_view(
3004 shell: &Shell,
3005 user: &AuthenticatedUser,
3006 default_tz: Tz,
3007 default_locale: &str,
3008 offered: &[String],
3009 account: AccountSecurity,
3010 min_password: usize,
3011) -> PreferencesTemplate {
3012 let current = user.user.timezone.as_deref();
3013 let zones = TZ_VARIANTS
3014 .iter()
3015 .filter(|tz| zone_offered(tz.name()))
3016 .map(|tz| TzOption {
3017 name: tz.name().to_string(),
3018 selected: current == Some(tz.name()),
3019 })
3020 .collect();
3021 let current_locale = user.user.locale.as_deref();
3022 let locales = offered
3023 .iter()
3024 .map(|code| LocaleOption {
3025 name: locale_name(code),
3026 selected: current_locale == Some(code.as_str()),
3027 code: code.clone(),
3028 })
3029 .collect();
3030 PreferencesTemplate {
3031 shell: shell.clone(),
3032 zones,
3033 effective_tz: shell.tz.name().to_string(),
3034 default_tz: default_tz.name().to_string(),
3035 inherits: current.is_none(),
3036 locales,
3037 default_locale: locale_name(default_locale),
3038 inherits_locale: current_locale.is_none(),
3039 sessions: account.sessions,
3040 password_changed: account.password_changed,
3041 must_change: account.must_change,
3042 min_password: min_password as i64,
3043 }
3044}
3045
3046struct AccountSecurity {
3049 sessions: Vec<SessionRow>,
3050 password_changed: Option<String>,
3051 must_change: bool,
3053}
3054
3055async fn account_security(
3056 state: &AdminState,
3057 user: &AuthenticatedUser,
3058 shell: &Shell,
3059 jar: &CookieJar,
3060) -> AccountSecurity {
3061 let locale = list::date_locale(shell.locale());
3062 let password_changed = match state.auth.password_changed_at(user.user.id).await {
3063 Ok(at) => {
3064 at.map(|dt| list::format_ts(&dt.to_rfc3339(), shell.tz, locale, "%-d %b %Y, %H:%M"))
3065 }
3066 Err(e) => {
3067 tracing::error!(error = %e, "reading the password change time failed");
3068 None
3069 }
3070 };
3071 AccountSecurity {
3072 sessions: session_rows(state, user, shell, jar).await,
3073 password_changed,
3074 must_change: state
3075 .auth
3076 .must_change_password(user.user.id)
3077 .await
3078 .unwrap_or(false),
3079 }
3080}
3081
3082async fn session_rows(
3085 state: &AdminState,
3086 user: &AuthenticatedUser,
3087 shell: &Shell,
3088 jar: &CookieJar,
3089) -> Vec<SessionRow> {
3090 let token = jar
3091 .get(SESSION_COOKIE)
3092 .map(|c| c.value().to_string())
3093 .unwrap_or_default();
3094 let locale = list::date_locale(shell.locale());
3095 let stamp = |dt: chrono::DateTime<chrono::Utc>| {
3096 list::format_ts(&dt.to_rfc3339(), shell.tz, locale, "%-d %b %Y, %H:%M")
3097 };
3098 match state.auth.list_sessions(user.user.id, &token).await {
3099 Ok(sessions) => sessions
3100 .into_iter()
3101 .map(|s| SessionRow {
3102 id: s.id,
3103 started: stamp(s.created_at),
3104 last_seen: stamp(s.last_seen_at),
3105 expires: stamp(s.expires_at),
3106 device: clientip::describe(s.user_agent.as_deref())
3107 .or(s.user_agent)
3108 .unwrap_or_else(|| "-".to_string()),
3109 ip_address: s.ip_address.unwrap_or_default(),
3110 current: s.current,
3111 })
3112 .collect(),
3113 Err(e) => {
3114 tracing::error!(error = %e, "listing sessions failed");
3115 Vec::new()
3116 }
3117 }
3118}
3119
3120fn builtin_resources() -> Vec<Resource> {
3122 vec![
3123 Resource {
3124 base_path: "/users".to_string(),
3125 nav_label: "Backend Users".into(),
3126 list: backend_users_list_config(),
3127 form: None,
3128 permission: Some("backend.manage_users".to_string()),
3129 },
3130 Resource {
3131 base_path: "/roles".to_string(),
3132 nav_label: "Roles".into(),
3133 list: roles_list_config(),
3134 form: None,
3137 permission: Some("backend.manage_roles".to_string()),
3138 },
3139 resource!("descriptors/audit-log.yaml"),
3140 resource!("descriptors/access-log.yaml"),
3141 ]
3142}
3143
3144fn builtin_settings() -> Vec<settings::SettingsItem> {
3148 vec![
3149 settings::SettingsItem::new("backend.administrators", "Administrators", Vec::new())
3150 .description("Manage backend administrator accounts.")
3151 .category("Users")
3152 .order(10)
3153 .icon("users")
3154 .permission("backend.manage_users")
3155 .link("/users"),
3156 settings::SettingsItem::new("backend.roles", "Roles", Vec::new())
3157 .description("Manage roles and their permissions.")
3158 .category("Users")
3159 .order(20)
3160 .icon("shield")
3161 .permission("backend.manage_roles")
3162 .link("/roles"),
3163 settings::brand::settings_item(),
3164 settings::SettingsItem::new("backend.plugins", "Plugins", Vec::new())
3165 .description("Enable or disable installed plugins.")
3166 .category("System")
3167 .order(10)
3168 .icon("plug")
3169 .permission(plugins::MANAGE_PERMISSION)
3170 .link("/plugins"),
3171 settings::SettingsItem::new("backend.audit_log", "Audit Log", Vec::new())
3172 .description("Review the record of administrative changes.")
3173 .category("System")
3174 .order(20)
3175 .icon("history")
3176 .permission("backend.view_audit_log")
3177 .link("/audit-log"),
3178 settings::SettingsItem::new("backend.access_log", "Access Log", Vec::new())
3179 .description("Review sign-ins, failures and lockouts.")
3180 .category("System")
3181 .order(30)
3182 .icon("log-in")
3183 .permission("backend.view_access_log")
3184 .link("/access-log"),
3185 ]
3186}
3187
3188fn backend_users_list_config() -> list::ListConfig {
3189 list::ListConfig {
3190 entity: "backend_users".to_string(),
3191 title: "Backend Users".into(),
3192 columns: vec![
3193 list::ListColumn::new("username", "Username"),
3194 list::ListColumn::new("email", "Email"),
3195 list::ListColumn::new("first_name", "First name"),
3196 list::ListColumn::new("last_name", "Last name"),
3197 list::ListColumn::new("is_superuser", "Superuser").yes_no(),
3198 list::ListColumn::new("is_active", "Active").yes_no(),
3199 list::ListColumn::new("created_at", "Created").datetime(),
3200 ],
3201 order_by: "created_at".to_string(),
3202 creatable: true,
3205 edit_base: Some("/users".to_string()),
3206 filters: vec![
3207 list::ListFilter::boolean("is_active", "Active"),
3208 list::ListFilter::boolean("is_superuser", "Superuser"),
3209 ],
3210 ..Default::default()
3214 }
3215}
3216
3217fn roles_list_config() -> list::ListConfig {
3218 list::ListConfig {
3219 entity: "backend_roles".to_string(),
3220 title: "Roles".into(),
3221 columns: vec![
3222 list::ListColumn::new("code", "Code"),
3223 list::ListColumn::new("name", "Name"),
3224 list::ListColumn::new("created_at", "Created").datetime(),
3225 ],
3226 order_by: "created_at".to_string(),
3227 edit_base: Some("/roles".to_string()),
3228 creatable: true,
3229 deletable: true,
3230 ..Default::default()
3231 }
3232}
3233
3234#[derive(Template)]
3235#[template(path = "login.html")]
3236struct LoginTemplate {
3237 base: String,
3239 asset_urls: Arc<AssetUrls>,
3241 brand: String,
3242 error: Option<String>,
3243 notice: Option<String>,
3245 i18n: Translator,
3248}
3249
3250fn preauth_asset(urls: &AssetUrls, base: &str, key: &str) -> String {
3253 match urls.get(key) {
3254 Some(path) => format!("{base}/assets/{path}"),
3255 None => {
3256 debug_assert!(false, "asset key `{key}` is not registered");
3257 format!("{base}/assets/{key}")
3258 }
3259 }
3260}
3261
3262impl LoginTemplate {
3263 fn asset(&self, key: &str) -> String {
3264 preauth_asset(&self.asset_urls, &self.base, key)
3265 }
3266 fn t(&self, source: &str) -> String {
3267 self.i18n.t(&Text::dynamic(source))
3268 }
3269 fn locale(&self) -> &str {
3270 self.i18n.locale()
3271 }
3272}
3273
3274#[derive(Template)]
3275#[template(path = "dashboard.html")]
3276struct DashboardTemplate {
3277 shell: Shell,
3278 username: String,
3279}
3280
3281#[derive(Template)]
3282#[template(path = "setup.html")]
3283struct SetupTemplate {
3284 base: String,
3286 asset_urls: Arc<AssetUrls>,
3288 brand: String,
3289 zones: Vec<TzOption>,
3290 error: Option<String>,
3291 i18n: Translator,
3293 min_password: i64,
3295}
3296
3297impl SetupTemplate {
3298 fn tf(&self, source: &str, args: &[(&'static str, i64)]) -> String {
3301 let mut text = Text::dynamic(source);
3302 for (name, value) in args {
3303 text = text.arg(*name, *value);
3304 }
3305 self.i18n.t(&text)
3306 }
3307
3308 fn asset(&self, key: &str) -> String {
3309 preauth_asset(&self.asset_urls, &self.base, key)
3310 }
3311 fn t(&self, source: &str) -> String {
3312 self.i18n.t(&Text::dynamic(source))
3313 }
3314 fn locale(&self) -> &str {
3315 self.i18n.locale()
3316 }
3317}
3318
3319#[derive(Template)]
3320#[template(path = "preferences.html")]
3321struct PreferencesTemplate {
3322 shell: Shell,
3323 zones: Vec<TzOption>,
3324 effective_tz: String,
3326 default_tz: String,
3328 inherits: bool,
3330 locales: Vec<LocaleOption>,
3331 default_locale: String,
3333 inherits_locale: bool,
3335 sessions: Vec<SessionRow>,
3337 password_changed: Option<String>,
3339 must_change: bool,
3341 min_password: i64,
3343}
3344
3345struct SessionRow {
3347 id: String,
3348 started: String,
3349 last_seen: String,
3350 expires: String,
3351 device: String,
3354 ip_address: String,
3356 current: bool,
3357}
3358
3359struct TzOption {
3360 name: String,
3361 selected: bool,
3362}
3363
3364struct LocaleOption {
3365 code: String,
3367 name: String,
3369 selected: bool,
3370}
3371
3372#[derive(Clone)]
3373struct NavView {
3374 label: String,
3375 path: String,
3376 active: bool,
3377 icon: String,
3380}
3381
3382pub(crate) fn render<T: Template>(template: T) -> Response {
3384 match template.render() {
3385 Ok(html) => Html(html).into_response(),
3386 Err(e) => AdminError::from(e).into_response(),
3388 }
3389}
3390
3391pub(crate) fn render_error() -> Response {
3392 error::masked_500()
3393}
3394
3395pub(crate) fn not_found() -> Response {
3396 AdminError::NotFound.into_response()
3397}
3398
3399pub(crate) fn forbidden() -> Response {
3400 AdminError::Forbidden.into_response()
3401}
3402
3403#[cfg(test)]
3404mod tests {
3405 use super::*;
3406
3407 fn write_form() -> form::FormConfig {
3408 form::FormConfig {
3409 enter: Default::default(),
3410 entity: "widgets".to_string(),
3411 title: "Widgets".into(),
3412 base_path: "/widgets".to_string(),
3413 id_field: "id".to_string(),
3414 fields: vec![],
3415 persist: None,
3416 timestamps: false,
3417 }
3418 }
3419
3420 fn resource_with(form: Option<form::FormConfig>, permission: Option<&str>) -> Resource {
3421 Resource {
3422 base_path: "/widgets".to_string(),
3423 nav_label: "Widgets".into(),
3424 list: backend_users_list_config(),
3425 form,
3426 permission: permission.map(str::to_string),
3427 }
3428 }
3429
3430 #[test]
3431 #[should_panic(expected = "must declare a permission")]
3432 fn write_resource_without_permission_aborts_boot() {
3433 let resource = resource_with(Some(write_form()), None);
3436 let _ = mount_resource(
3437 &resource,
3438 &field::builtin_registry(),
3439 &list::builtin_column_registry(),
3440 &std::collections::HashSet::new(),
3441 &persist::PersisterRegistry::new(),
3442 &[],
3443 );
3444 }
3445
3446 #[test]
3448 fn the_access_log_is_read_from_its_descriptor_file() {
3449 let access = builtin_resources()
3450 .into_iter()
3451 .find(|r| r.base_path == "/access-log")
3452 .expect("the access log is registered");
3453 assert_eq!(access.list.entity, "backend_access_log");
3454 assert_eq!(
3455 access.permission.as_deref(),
3456 Some("backend.view_access_log")
3457 );
3458 assert!(access.form.is_none(), "append-only");
3459 assert_eq!(
3460 access
3461 .list
3462 .columns
3463 .iter()
3464 .map(|c| c.field.as_str())
3465 .collect::<Vec<_>>(),
3466 [
3467 "created_at",
3468 "username_attempted",
3469 "event",
3470 "ip_address",
3471 "user_agent"
3472 ]
3473 );
3474 }
3475
3476 #[test]
3479 fn the_audit_log_is_read_from_its_descriptor_file() {
3480 let audit = builtin_resources()
3481 .into_iter()
3482 .find(|r| r.base_path == "/audit-log")
3483 .expect("the audit log is registered");
3484 assert_eq!(audit.list.entity, "backend_audit_log");
3485 assert_eq!(audit.permission.as_deref(), Some("backend.view_audit_log"));
3486 assert_eq!(
3487 audit
3488 .list
3489 .columns
3490 .iter()
3491 .map(|c| c.field.as_str())
3492 .collect::<Vec<_>>(),
3493 [
3494 "created_at",
3495 "actor_username",
3496 "action",
3497 "target_type",
3498 "target_id",
3499 "target_label"
3500 ],
3501 "in the order the file writes them"
3502 );
3503 assert_eq!(audit.list.columns[0].column_type, "datetime");
3504 assert_eq!(audit.list.per_page, 50);
3505 assert_eq!(audit.list.per_page_options, [25, 50, 100]);
3506 assert!(audit.list.exportable, "evidence may leave the panel");
3507 assert!(audit.form.is_none(), "append-only: no form");
3508 assert!(!audit.list.deletable, "and nothing removes from it");
3509 }
3510
3511 #[test]
3512 #[should_panic(expected = "uses unregistered type `nope`")]
3513 fn unregistered_column_type_aborts_boot() {
3514 let mut resource = resource_with(None, None);
3515 let mut score = list::ListColumn::new("score", "Score");
3516 score.column_type = "nope".into();
3517 resource.list.columns.push(score);
3518 let _ = mount_resource(
3519 &resource,
3520 &field::builtin_registry(),
3521 &list::builtin_column_registry(),
3522 &std::collections::HashSet::new(),
3523 &persist::PersisterRegistry::new(),
3524 &[],
3525 );
3526 }
3527
3528 #[test]
3529 fn read_only_resource_may_omit_permission() {
3530 let resource = resource_with(None, None);
3532 let _ = mount_resource(
3533 &resource,
3534 &field::builtin_registry(),
3535 &list::builtin_column_registry(),
3536 &std::collections::HashSet::new(),
3537 &persist::PersisterRegistry::new(),
3538 &[],
3539 );
3540 }
3541
3542 #[test]
3543 fn shell_localizes_through_the_translator_and_falls_back() {
3544 let shell = Shell::test();
3546 assert_eq!(shell.t("Save"), "Save");
3547 assert_eq!(shell.tt(&Text::dynamic("Discard")), "Discard");
3548 }
3549
3550 #[test]
3551 fn shell_tf_interpolates_integer_arguments() {
3552 let shell = Shell::test();
3553 assert_eq!(
3554 shell.tf("Page {page} of {pages}", &[("page", 2), ("pages", 5)]),
3555 "Page 2 of 5"
3556 );
3557 }
3558
3559 #[test]
3560 fn display_tz_prefers_a_valid_operator_preference() {
3561 assert_eq!(
3562 resolve_display_tz(Some("Asia/Kolkata"), Tz::UTC),
3563 Tz::Asia__Kolkata
3564 );
3565 }
3566
3567 #[test]
3568 fn display_tz_falls_back_when_unset_or_invalid() {
3569 let default = Tz::Europe__London;
3570 assert_eq!(resolve_display_tz(None, default), default);
3572 assert_eq!(resolve_display_tz(Some("Not/AZone"), default), default);
3574 assert_eq!(resolve_display_tz(Some(""), default), default);
3575 }
3576
3577 #[test]
3578 fn accept_language_orders_by_weight_and_drops_wildcard() {
3579 assert_eq!(
3580 parse_accept_language("en-US,en;q=0.9,kn;q=0.8"),
3581 vec!["en-US", "en", "kn"]
3582 );
3583 assert_eq!(
3585 parse_accept_language("en;q=0.5,kn,*;q=0.1"),
3586 vec!["kn", "en"]
3587 );
3588 }
3589
3590 #[test]
3591 fn locale_chain_prefers_operator_then_header_then_default() {
3592 let loaded = ["hi".to_string(), "kn".to_string(), "ta".to_string()];
3594 assert_eq!(
3597 resolve_locale_chain(Some("kn"), Some("ta;q=0.9,hi;q=0.8"), "en", &loaded),
3598 vec!["kn", "ta", "hi", "en"]
3599 );
3600 assert_eq!(
3602 resolve_locale_chain(Some("kn"), Some("en;q=0.9"), "ta", &loaded),
3603 vec!["kn", "en", "ta"]
3604 );
3605 assert_eq!(
3607 resolve_locale_chain(Some("kn-IN"), None, "en", &loaded),
3608 vec!["kn", "en"]
3609 );
3610 }
3611
3612 #[test]
3613 fn locale_chain_skips_unserveable_and_defaults_to_en() {
3614 let loaded = ["hi".to_string()];
3616 assert_eq!(
3619 resolve_locale_chain(Some("fr"), Some("de,es"), "zz", &loaded),
3620 vec!["en"]
3621 );
3622 assert_eq!(resolve_locale_chain(None, None, "en", &loaded), vec!["en"]);
3624 assert_eq!(
3626 resolve_locale_chain(Some("hi"), None, "en", &loaded),
3627 vec!["hi", "en"]
3628 );
3629 assert_eq!(
3631 resolve_locale_chain(Some(laterite_core::PSEUDO_LOCALE), None, "en", &loaded),
3632 vec![laterite_core::PSEUDO_LOCALE, "en"]
3633 );
3634 }
3635
3636 #[test]
3637 fn page_assets_dedupe_preserve_order_and_classify() {
3638 let mut reg = AssetRegistry::new();
3639 reg.insert(
3640 "a.js",
3641 AdminAsset {
3642 mime: "text/javascript; charset=utf-8",
3643 bytes: std::borrow::Cow::Borrowed(b"//"),
3644 },
3645 );
3646 reg.insert(
3647 "b.css",
3648 AdminAsset {
3649 mime: "text/css; charset=utf-8",
3650 bytes: std::borrow::Cow::Borrowed(b"body{}"),
3651 },
3652 );
3653 let urls = asset_urls(®);
3656 let assets = page_assets(&["a.js", "b.css", "a.js"], "/admin", ®, &urls);
3657 assert_eq!(assets.len(), 2);
3658 assert_eq!(
3659 assets[0].url,
3660 format!("/admin/assets/a.{}.js", http_cache::digest(b"//"))
3661 );
3662 assert!(!assets[0].css);
3663 assert_eq!(
3664 assets[1].url,
3665 format!("/admin/assets/b.{}.css", http_cache::digest(b"body{}"))
3666 );
3667 assert!(assets[1].css);
3668 assert_ne!(assets[0].url, assets[1].url);
3671 }
3672
3673 async fn empty_db() -> (Db, laterite_core::testing::TestGuard) {
3677 laterite_core::testing::connect_test(&[]).await
3678 }
3679
3680 #[tokio::test]
3681 async fn builtin_migrations_create_the_admin_tables() {
3682 let (db, _guard) = empty_db().await;
3683 laterite_core::migration::run(&db.pool, db.backend, &builtin_migrations())
3684 .await
3685 .unwrap();
3686 for table in ["backend_users", "settings"] {
3690 let probe = sqlx::query(&format!("select 1 from {table} where 1 = 0"))
3691 .fetch_optional(&db.pool)
3692 .await;
3693 assert!(
3694 probe.is_ok(),
3695 "{table} should exist after builtin_migrations"
3696 );
3697 }
3698 }
3699
3700 #[tokio::test]
3701 async fn brand_setting_overrides_config_and_blank_falls_back() {
3702 let (db, _guard) = laterite_core::testing::connect_test(&[settings::migrations()]).await;
3703 let state = AdminState {
3704 auth: AuthService::new(db.clone(), laterite_auth::AuthConfig::default()),
3705 db: db.clone(),
3706 nav: Arc::new(Vec::new()),
3707 settings: Arc::new(Vec::new()),
3708 permissions: Arc::new(builtin_permissions()),
3709 trusted_proxies: Arc::new(Vec::new()),
3710 icons: Arc::new(laterite_core::icons::IconSet::new()),
3711 sprite_url: Arc::from(""),
3712 admin_path: Arc::from("/admin"),
3713 secure_cookie: false,
3714 origin: Arc::from(""),
3715 timezone: Tz::UTC,
3716 default_locale: Arc::from("en"),
3717 catalogs: Arc::new(CatalogStore::default()),
3718 app_name: "Configured Name".to_string(),
3719 brand_cache: Arc::new(RwLock::new(None)),
3720 field_types: Arc::new(field::builtin_registry()),
3721 column_types: Arc::new(list::builtin_column_registry()),
3722 plugin_defined: Arc::new(laterite_core::Registry::new()),
3723 assets: Arc::new(builtin_assets()),
3724 asset_urls: Arc::new(asset_urls(&builtin_assets())),
3725 pickers: Arc::new(picker::PickerRegistry::new()),
3726 overrides: Arc::new(field::NoOverrides),
3727 };
3728
3729 assert_eq!(state.brand().await, "Configured Name");
3731
3732 settings::store::save(
3735 &db,
3736 &settings::BrandSetting {
3737 app_name: "Acme Corp".to_string(),
3738 },
3739 )
3740 .await
3741 .unwrap();
3742 state.invalidate_brand();
3743 assert_eq!(state.brand().await, "Acme Corp");
3744
3745 settings::store::save(
3747 &db,
3748 &settings::BrandSetting {
3749 app_name: " ".to_string(),
3750 },
3751 )
3752 .await
3753 .unwrap();
3754 state.invalidate_brand();
3755 assert_eq!(state.brand().await, "Configured Name");
3756 }
3757
3758 fn settings_item(code: &str, permission: Option<&str>) -> settings::SettingsItem {
3759 settings::SettingsItem {
3760 code: code.to_string(),
3761 label: code.into(),
3762 description: String::new().into(),
3763 category: "General".into(),
3764 hint: None,
3765 order: 1,
3766 icon: None,
3767 permission: permission.map(str::to_string),
3768 link: None,
3769 fields: Vec::new(),
3770 route: None,
3771 }
3772 }
3773
3774 #[test]
3775 fn settings_visibility_respects_permissions() {
3776 let items = vec![
3777 settings_item("public", None),
3778 settings_item("gated", Some("backend.manage_users")),
3779 ];
3780
3781 let none = PermissionSet::new(false, Vec::<String>::new());
3783 let codes: Vec<String> = visible_settings(&items, &none)
3784 .into_iter()
3785 .map(|i| i.code)
3786 .collect();
3787 assert_eq!(codes, ["public"]);
3788
3789 let granted = PermissionSet::new(false, ["backend.manage_users".to_string()]);
3791 assert_eq!(visible_settings(&items, &granted).len(), 2);
3792
3793 let superuser = PermissionSet::new(true, Vec::<String>::new());
3795 assert_eq!(visible_settings(&items, &superuser).len(), 2);
3796 }
3797
3798 #[test]
3799 fn context_sidebar_follows_settings_links() {
3800 let items = builtin_settings();
3801 let superuser = PermissionSet::new(true, Vec::<String>::new());
3802 let tr = Translator::new("en");
3803 let sidebar = |path: &str| {
3804 resolve_nav_context(
3805 &[],
3806 &items,
3807 "/admin",
3808 &superuser,
3809 path,
3810 &tr,
3811 icons::Icons::new(&laterite_core::icons::IconSet::new(), "/s.svg"),
3812 )
3813 .0
3814 };
3815 let active_path = |path: &str| -> Option<String> {
3816 sidebar(path)
3817 .into_iter()
3818 .flat_map(|g| g.items)
3819 .find(|i| i.active)
3820 .map(|i| i.path)
3821 };
3822
3823 assert_eq!(active_path("/admin/users").as_deref(), Some("/admin/users"));
3825 assert_eq!(
3826 active_path("/admin/roles/42/edit").as_deref(),
3827 Some("/admin/roles")
3828 );
3829 assert!(!sidebar("/admin/settings").is_empty());
3831 assert_eq!(active_path("/admin/settings"), None);
3832 assert_eq!(
3837 active_path("/admin/settings/branding").as_deref(),
3838 Some("/admin/settings/branding")
3839 );
3840 assert_eq!(active_path("/admin/settings/laterite.brand"), None);
3843 assert_eq!(active_path("/admin/settings/laterite/brand"), None);
3844 assert!(sidebar("/admin").is_empty());
3846 }
3847
3848 #[test]
3849 fn active_nav_lights_the_right_tab() {
3850 let nav = vec![
3851 NavLink {
3852 label: "Dashboard".into(),
3853 path: "/admin".to_string(),
3854 icon: Some("layout-dashboard"),
3855 },
3856 NavLink {
3857 label: "Pages".into(),
3858 path: "/admin/pages".to_string(),
3859 icon: None,
3860 },
3861 NavLink {
3862 label: "Settings".into(),
3863 path: "/admin/settings".to_string(),
3864 icon: Some("settings"),
3865 },
3866 ];
3867
3868 assert_eq!(
3870 active_nav_path(&nav, "/admin", false, "/admin").as_deref(),
3871 Some("/admin")
3872 );
3873 assert_eq!(
3875 active_nav_path(&nav, "/admin", false, "/admin/pages/7/edit").as_deref(),
3876 Some("/admin/pages")
3877 );
3878 assert_eq!(
3880 active_nav_path(&nav, "/admin", false, "/admin/pages-archive"),
3881 None
3882 );
3883 assert_eq!(
3886 active_nav_path(&nav, "/admin", false, "/admin/preferences"),
3887 None
3888 );
3889 assert_eq!(
3892 active_nav_path(&nav, "/admin", true, "/admin/users").as_deref(),
3893 Some("/admin/settings")
3894 );
3895 assert_eq!(
3896 active_nav_path(&nav, "/admin", true, "/admin/settings").as_deref(),
3897 Some("/admin/settings")
3898 );
3899 }
3900}
3901
3902#[cfg(test)]
3903mod session_cookie_tests {
3904 use super::*;
3905
3906 #[test]
3910 fn the_session_cookie_never_outlives_the_browser() {
3911 let cookie = session_cookie("tok".into(), "/admin", false);
3912 assert_eq!(cookie.max_age(), None);
3913 assert!(cookie.http_only().unwrap_or(false));
3914 assert_eq!(cookie.path(), Some("/admin"));
3915 }
3916
3917 #[test]
3920 fn the_remember_cookie_carries_its_own_lifetime() {
3921 let credential = laterite_auth::RememberCredential {
3922 cookie: "sel:ver".into(),
3923 expires_at: chrono::Utc::now() + chrono::Duration::days(14),
3924 };
3925 let cookie = remember_cookie(credential, "/admin", true);
3926 let age = cookie.max_age().expect("a remember cookie must persist");
3927 assert!((age.whole_seconds() - 14 * 24 * 60 * 60).abs() <= 1);
3929 assert!(cookie.http_only().unwrap_or(false));
3930 assert!(cookie.secure().unwrap_or(false));
3931 }
3932
3933 #[test]
3935 fn the_removal_matches_the_cookie_it_clears() {
3936 let removal = remember_removal("/admin");
3937 assert_eq!(removal.name(), REMEMBER_COOKIE);
3938 assert_eq!(removal.path(), Some("/admin"));
3939 }
3940}