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