Skip to main content

laterite_admin/
lib.rs

1//! Laterite admin: the operator-facing web surface.
2//!
3//! An Axum router mounted under a configurable path (default `/admin`, set by
4//! [`AdminConfig::path`]): a login screen and session cookie verified against
5//! `laterite-auth`, and descriptor-driven screens.
6//!
7//! Screens are **resources**: a module declares a [`Resource`] (a
8//! [`list::ListConfig`], optionally a [`form::FormConfig`], a base path, and a
9//! menu label), and the framework mounts the list, create, and edit routes and
10//! adds it to the menu. This is the extension point that lets an application
11//! contribute its own admin screens. The framework's own screens (users, roles)
12//! are just built-in resources.
13//!
14//! An application usually boots through [`Bootstrap`], which loads config,
15//! connects, migrates, and serves this router in one call.
16
17mod 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 mod import;
31pub(crate) mod keyed;
32pub mod list;
33pub mod nav;
34pub(crate) mod palette;
35pub mod persist;
36pub mod picker;
37pub mod plugins;
38pub mod relation;
39pub(crate) mod requestlog;
40mod roles;
41mod routemap;
42pub mod routes;
43mod session;
44pub mod settings;
45mod sql;
46pub mod ui;
47mod upload;
48mod users;
49
50/// The axum a contributed route must build against.
51///
52/// A [`Screen`](routes::Screen) or [`PublicRoute`](routes::PublicRoute) returns an
53/// `axum::Router`, so a plugin needs the type. Take it from here and never declare
54/// axum in a plugin manifest: two majors linked side by side make `Router` a
55/// different type from `Router`, and the diagnostic for that is famously unhelpful.
56/// Re-exported so this crate's manifest is the only place the version is chosen.
57pub use axum;
58
59pub use bootstrap::{AppConfig, Bootstrap, BootstrapCtx, DEFAULT_ENV_PREFIX};
60pub use error::AdminError;
61pub use session::{FlashLevel, SessionHandle};
62pub use upload::VerifiedUpload;
63
64use std::collections::HashMap;
65use std::sync::{Arc, RwLock};
66
67use askama::Template;
68use axum::body::Body;
69use axum::extract::{Path, Query, Request, State};
70use axum::http::{header, HeaderMap};
71use axum::middleware::{self, Next};
72use axum::response::{Html, IntoResponse, Redirect, Response};
73use axum::routing::{any, get, post};
74use axum::{Extension, Form, Router};
75use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
76use chrono_tz::{Tz, TZ_VARIANTS};
77use laterite_auth::{AuthService, AuthenticatedUser, NewOperator, PermissionSet, RequestContext};
78use laterite_core::{t, CatalogStore, Db, Text, Translator};
79use serde::{Deserialize, Serialize};
80
81/// Typed contribution channels for the framework's admin surfaces, as an
82/// extension trait over the generic [`laterite_core::Registry`]. A module
83/// contributes its admin screens, permissions, and settings from its `register`;
84/// a wrong-type contribution is a compile error, not one silently ignored. The
85/// generic `add`/`items` underneath remains for open, plugin-defined points.
86pub trait AdminRegistry {
87    /// Adds a list/form resource (an admin screen).
88    fn add_resource(&mut self, resource: Resource);
89    /// Adds a permission, offered in the role editor.
90    fn add_permission(&mut self, permission: Permission);
91    /// Adds a settings model.
92    fn add_settings(&mut self, item: settings::SettingsItem);
93    /// Adds a reference-picker source, callable by a picker field's endpoints.
94    fn add_picker_source(&mut self, source: picker::PickerSourceReg);
95    /// Adds a form persister, selectable by a form descriptor's `persist` key.
96    fn add_persister(&mut self, persister: persist::PersisterReg);
97    /// Adds a field type, nameable by any form or settings descriptor.
98    fn add_field_type(&mut self, field_type: field::FieldTypeReg);
99    /// Mounts a screen of this module's own: any routes descriptors cannot
100    /// express, inside the admin with its session, permission and error handling.
101    fn add_screen(&mut self, screen: routes::ScreenReg);
102    /// Mounts a route outside the admin, at a literal path: robots.txt, a
103    /// sitemap, a feed, a webhook receiver.
104    fn add_public_route(&mut self, route: routes::PublicRouteReg);
105    /// Adds a menu entry or section. See [`nav::NavItem`].
106    fn add_nav(&mut self, item: nav::NavItem);
107    /// Changes another module's resource before it mounts. See [`ResourceHook`].
108    fn add_resource_hook(&mut self, hook: ResourceHook);
109}
110
111impl AdminRegistry for laterite_core::Registry {
112    fn add_resource(&mut self, resource: Resource) {
113        self.add(resource);
114    }
115    fn add_permission(&mut self, permission: Permission) {
116        self.add(permission);
117    }
118    fn add_settings(&mut self, item: settings::SettingsItem) {
119        self.add(item);
120    }
121    fn add_picker_source(&mut self, source: picker::PickerSourceReg) {
122        self.add(source);
123    }
124    fn add_screen(&mut self, screen: routes::ScreenReg) {
125        self.add(screen);
126    }
127    fn add_public_route(&mut self, route: routes::PublicRouteReg) {
128        self.add(route);
129    }
130    fn add_nav(&mut self, item: nav::NavItem) {
131        self.add(item);
132    }
133    fn add_resource_hook(&mut self, hook: ResourceHook) {
134        self.add(hook);
135    }
136    fn add_persister(&mut self, persister: persist::PersisterReg) {
137        self.add(persister);
138    }
139    fn add_field_type(&mut self, field_type: field::FieldTypeReg) {
140        self.add(field_type);
141    }
142}
143
144/// A change to another module's resource, applied at boot before the resource
145/// mounts: the hook receives the resource as declared and returns it changed,
146/// so a module adds a column, a field, a relation or a menu placement to a
147/// screen it does not own. The target is the resource's path as it mounts
148/// (`/posts`; a plugin's under its module base, `/acme/blog/posts`). A target
149/// nobody declared aborts boot. Hooks run in module order.
150#[derive(Clone)]
151pub struct ResourceHook {
152    pub target: String,
153    apply: Arc<dyn Fn(Resource) -> Resource + Send + Sync>,
154}
155
156impl ResourceHook {
157    pub fn new(
158        target: impl Into<String>,
159        apply: impl Fn(Resource) -> Resource + Send + Sync + 'static,
160    ) -> Self {
161        Self {
162            target: target.into(),
163            apply: Arc::new(apply),
164        }
165    }
166
167    /// Applies the hook to `resource`.
168    pub fn apply(&self, resource: Resource) -> Resource {
169        (self.apply)(resource)
170    }
171}
172
173impl std::fmt::Debug for ResourceHook {
174    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
175        write!(f, "ResourceHook({})", self.target)
176    }
177}
178
179const SESSION_COOKIE: &str = "laterite_session";
180/// The long-lived "stay signed in" credential. Separate from the session cookie
181/// so the session itself stays short and the credential can be rotated and
182/// revoked on its own.
183const REMEMBER_COOKIE: &str = "laterite_remember";
184
185/// The icon sprite's registry key. One request, cached forever, in place of a
186/// few hundred bytes of repeated markup per icon per render.
187pub(crate) const ICON_SPRITE: &str = "icons.svg";
188
189/// Shared state for the admin router. Constructed by [`router`].
190#[derive(Clone)]
191pub(crate) struct AdminState {
192    auth: AuthService,
193    db: Db,
194    nav: Arc<nav::NavTree>,
195    settings: Arc<Vec<settings::SettingsItem>>,
196    permissions: Arc<Vec<Permission>>,
197    /// The URL path the panel is mounted under, without a trailing slash (e.g.
198    /// `/admin`). Every route, redirect, link, and the session-cookie scope is
199    /// built from it, so one config value moves the whole panel.
200    admin_path: Arc<str>,
201    secure_cookie: bool,
202    /// Networks whose `X-Forwarded-For` is believed. Parsed once at boot.
203    trusted_proxies: Arc<Vec<ipnet::IpNet>>,
204    /// The framework's icon set plus whatever modules contributed.
205    icons: Arc<laterite_core::icons::IconSet>,
206    /// Where the sprite is served, content-named. Resolved once at boot.
207    sprite_url: Arc<str>,
208    /// The public origin for the CSRF origin check (see [`AdminConfig::origin`]).
209    origin: Arc<str>,
210    timezone: Tz,
211    /// The deployment default UI locale (a base tag like `en`), the last stop in a
212    /// request's locale chain before the English source. An operator's own
213    /// preference overrides it.
214    default_locale: Arc<str>,
215    /// The shared message catalogs, resolved once at boot and looked up per request
216    /// through the [`Translator`]. Empty until module catalogs are loaded.
217    catalogs: Arc<CatalogStore>,
218    /// The configured application name (the baseline brand). A brand setting
219    /// overrides it; see [`AdminState::brand`].
220    app_name: String,
221    /// The resolved brand name, cached across requests so the brand setting is
222    /// not read from the database on every page. Invalidated when the setting is
223    /// saved. `None` means "not resolved yet".
224    brand_cache: Arc<RwLock<Option<String>>>,
225    /// Each registered asset's content-named path. See [`asset_urls`].
226    asset_urls: Arc<AssetUrls>,
227    /// The field-type registry (built-ins plus contributions): resolves a form
228    /// descriptor's type key to its rendering + behaviour. See [`field`].
229    field_types: Arc<field::FieldRegistry>,
230    /// The column-type registry: resolves a list column's type key to its cell
231    /// rendering. Sibling to `field_types`; shares the override resolver.
232    column_types: Arc<list::ColumnRegistry>,
233    /// Contributions the framework does not consume, readable by a module's own
234    /// routes through `RouteCtx`.
235    plugin_defined: Arc<laterite_core::Registry>,
236    /// Embedded admin assets served under `{admin}/assets/` (see [`AdminAsset`]).
237    assets: Arc<AssetRegistry>,
238    /// The reference-picker source registry: resolves a picker field's `source`
239    /// key to the domain service its endpoints call. See [`picker`].
240    pickers: Arc<picker::PickerRegistry>,
241    /// The resources whose records the command palette finds, each through
242    /// the picker source it named. See [`palette`].
243    palette: Arc<Vec<palette::RecordSource>>,
244    /// The admin view-override resolver, default [`field::NoOverrides`] (the
245    /// compiled path). A theme layer injects a runtime-template-backed resolver
246    /// so users can override a field's presentation from outside the plugin.
247    overrides: Arc<dyn field::OverrideResolver>,
248}
249
250impl AdminState {
251    #[cfg(test)]
252    pub(crate) fn new(auth: AuthService, db: Db) -> Self {
253        Self {
254            auth,
255            db,
256            nav: Arc::new(nav::NavTree::default()),
257            settings: Arc::new(Vec::new()),
258            permissions: Arc::new(builtin_permissions()),
259            trusted_proxies: Arc::new(Vec::new()),
260            icons: Arc::new(laterite_core::icons::IconSet::new()),
261            sprite_url: Arc::from(""),
262            admin_path: Arc::from("/admin"),
263            secure_cookie: false,
264            origin: Arc::from(""),
265            timezone: Tz::UTC,
266            default_locale: Arc::from("en"),
267            catalogs: Arc::new(CatalogStore::default()),
268            app_name: "Laterite".to_string(),
269            brand_cache: Arc::new(RwLock::new(None)),
270            field_types: Arc::new(field::builtin_registry()),
271            column_types: Arc::new(list::builtin_column_registry()),
272            plugin_defined: Arc::new(laterite_core::Registry::new()),
273            assets: Arc::new(builtin_assets()),
274            asset_urls: Arc::new(asset_urls(&builtin_assets())),
275            pickers: Arc::new(picker::PickerRegistry::new()),
276            palette: Arc::new(Vec::new()),
277            overrides: Arc::new(field::NoOverrides),
278        }
279    }
280
281    /// The brand name shown across the admin: the [`settings::BrandSetting`]
282    /// `app_name` when set, otherwise the configured application name. The
283    /// resolved value is cached until [`AdminState::invalidate_brand`] clears it.
284    async fn brand(&self) -> String {
285        {
286            let cached = self.brand_cache.read().unwrap().clone();
287            if let Some(name) = cached {
288                return name;
289            }
290        }
291        let resolved = match settings::store::load::<settings::BrandSetting>(&self.db).await {
292            Ok(brand) if !brand.app_name.trim().is_empty() => brand.app_name,
293            _ => self.app_name.clone(),
294        };
295        *self.brand_cache.write().unwrap() = Some(resolved.clone());
296        resolved
297    }
298
299    /// Clears the cached brand so the next resolution re-reads the setting.
300    fn invalidate_brand(&self) {
301        *self.brand_cache.write().unwrap() = None;
302    }
303}
304
305/// Deployment-level admin settings passed to [`router`]. Per-install brand and
306/// per-operator preferences are settings/preferences, not deployment config.
307///
308/// Non-exhaustive: build one with [`Default`] and set fields, so a field added
309/// in a later release is additive.
310#[derive(Clone)]
311#[non_exhaustive]
312pub struct AdminConfig {
313    /// Set the `Secure` attribute on the session cookie. Enable behind HTTPS in
314    /// production; leave off for plain-HTTP local development.
315    pub secure_cookie: bool,
316    /// Networks whose `X-Forwarded-For` may be believed, as CIDR ranges. Empty
317    /// trusts nothing and records the peer address. See
318    /// [`laterite_core::config::BackendConfig::trusted_proxies`].
319    pub trusted_proxies: Vec<String>,
320    /// Default display timezone for the admin (an IANA name like `Asia/Kolkata`).
321    /// Storage is UTC; this only affects rendering. Invalid or empty falls back
322    /// to UTC. An operator's own preference overrides it (later).
323    pub timezone: String,
324    /// Default UI locale for the admin (a base tag like `en` or `de`). An
325    /// operator's own preference and the request's `Accept-Language` override it;
326    /// a locale with no loaded catalog, or an empty value, falls back to `en`.
327    pub locale: String,
328    /// The application name, shown as the admin brand. This is the baseline; a
329    /// `BrandSetting` in the admin overrides it. Typically the configured
330    /// `app.name`. Empty falls back to `Laterite`.
331    pub app_name: String,
332    /// The URL path the panel is mounted under (typically the configured
333    /// `backend.path`). A leading slash is added if missing and a trailing slash
334    /// is stripped; empty falls back to `/admin`.
335    pub path: String,
336    /// The public origin (scheme://host[:port], no trailing slash) the panel is
337    /// served from, for the CSRF origin check. Typically the configured
338    /// `app.url`; empty falls back to the request `Host` (dev only), so set it in
339    /// production.
340    pub origin: String,
341    /// The directory files the admin keeps are stored under, relative to the
342    /// working directory unless absolute (typically the configured
343    /// `backend.storage`). Uploaded import files go to `private` beneath it
344    /// when the application registers no disk of that name.
345    pub storage_dir: String,
346}
347
348impl Default for AdminConfig {
349    fn default() -> Self {
350        Self {
351            secure_cookie: false,
352            trusted_proxies: Vec::new(),
353            timezone: "UTC".to_string(),
354            locale: "en".to_string(),
355            app_name: "Laterite".to_string(),
356            path: "/admin".to_string(),
357            origin: String::new(),
358            storage_dir: "storage".to_string(),
359        }
360    }
361}
362
363/// The chrome shared by every authenticated page: the top-nav links and the
364/// signed-in operator. Built once by the auth guard and injected into request
365/// extensions, so page handlers render inside the same shell without each
366/// rebuilding it. Templates embed it as `shell` and `base.html` renders it.
367///
368/// A contributed screen takes it as `Extension<Shell>` and renders its own
369/// markup inside the chrome with [`Shell::page`]; [`Shell::t`] localizes its
370/// strings and [`Shell::csrf_token`] arms a form it builds by hand.
371#[derive(Clone)]
372pub struct Shell {
373    /// The admin mount path (e.g. `/admin`), so shared chrome (asset links, the
374    /// brand link, sign-out and preferences) builds URLs under the configured
375    /// panel path rather than a hardcoded `/admin`.
376    pub(crate) base: String,
377    /// The brand name shown in the top nav and drawer, resolved once per request
378    /// (the brand setting, or the configured application name). See
379    /// [`AdminState::brand`].
380    brand: String,
381    nav: Vec<NavView>,
382    full_name: String,
383    initial: String,
384    /// The timezone this operator's timestamps render in, resolved once per
385    /// request: the operator's own preference if set and valid, else the
386    /// deployment default. List and detail screens format dates in it.
387    tz: Tz,
388    /// The translator for this request's locale (resolved like `tz`), used by
389    /// `shell.t` / `shell.tt` in templates. A source with no catalog entry falls
390    /// back to itself.
391    i18n: Translator,
392    /// The context sidebar for the current section, resolved once per request
393    /// from the path (see [`resolve_nav_context`]). Empty means no sidebar.
394    /// `base.html` renders it, so any screen in a settings context shows it.
395    sidebar: Vec<settings::CategoryView>,
396    /// The way to this page: the active tab, then the active sidebar entry.
397    /// Rendered only when there are two, so a tab's own page shows none.
398    crumbs: Vec<CrumbView>,
399    /// The icon set, for chrome that renders one outside a nav entry.
400    pub(crate) icon_set: Arc<laterite_core::icons::IconSet>,
401    /// Where the sprite lives, so chrome can reference a glyph rather than
402    /// carry its drawing instructions.
403    pub(crate) sprite_url: Arc<str>,
404    /// The site's own root, so the chrome can offer a way out to the front of
405    /// the site an operator is administering. The configured `app.url` when set,
406    /// else derived from the bind address.
407    site_url: String,
408    /// Each asset's content-named path, so chrome in `base.html` links assets
409    /// through [`Shell::asset`] rather than by a stable path the browser would
410    /// be entitled to keep.
411    asset_urls: Arc<AssetUrls>,
412    /// The current session's CSRF token, auto-injected into every rendered form
413    /// (a hidden field) and into HTMX requests (a header), so a mutating request
414    /// carries it without the handler doing anything. See [`session`].
415    pub(crate) csrf_token: String,
416    /// Flash messages to show once on this render, taken from the session on a
417    /// full-page GET (redirect-after-POST delivers them here) and localized in this
418    /// request's locale. See [`session`].
419    pub(crate) flash: Vec<FlashLine>,
420    /// Per-page widget assets (field/column scripts and styles) for this render,
421    /// deduped and emitted in the head after core `laterite.js`. See
422    /// [`page_assets`].
423    pub(crate) assets: Vec<PageAsset>,
424}
425
426/// A contributed screen's markup inside the chrome. See [`Shell::page`].
427#[derive(Template)]
428#[template(path = "page.html")]
429struct PageTemplate {
430    title: String,
431    body: html::Markup,
432    shell: Shell,
433}
434
435/// One per-page asset to load: a resolved URL and whether it is a stylesheet.
436#[derive(Clone)]
437pub(crate) struct PageAsset {
438    pub(crate) url: String,
439    pub(crate) css: bool,
440}
441
442/// A flash message localized for this render: the session's stored `Text` resolved
443/// to a display string in the operator's locale. `base.html` renders it.
444#[derive(Clone)]
445pub(crate) struct FlashLine {
446    pub(crate) level: session::FlashLevel,
447    pub(crate) text: String,
448    /// Stays until dismissed.
449    pub(crate) sticky: bool,
450}
451
452impl Shell {
453    #[allow(clippy::too_many_arguments)]
454    fn new(
455        base: &str,
456        brand: String,
457        nav: &[nav::NavNode],
458        user: &AuthenticatedUser,
459        default_tz: Tz,
460        sidebar: Vec<settings::CategoryView>,
461        active_nav: Option<&str>,
462        csrf_token: String,
463        flash: Vec<session::Flash>,
464        i18n: Translator,
465        asset_urls: Arc<AssetUrls>,
466        site_url: String,
467        icon_set: Arc<laterite_core::icons::IconSet>,
468        sprite_url: Arc<str>,
469    ) -> Self {
470        let full_name = user.user.full_name();
471        let initial = full_name
472            .chars()
473            .next()
474            .map(|c| c.to_uppercase().to_string())
475            .unwrap_or_else(|| "?".to_string());
476        // Localize the flashes and nav labels here, where the request translator is
477        // in hand, before it is moved into the shell.
478        let flash = flash
479            .into_iter()
480            .map(|f| FlashLine {
481                sticky: f.sticky,
482                level: f.level,
483                text: i18n.t(&f.text),
484            })
485            .collect();
486        let nav: Vec<NavView> = nav
487            .iter()
488            .map(|n| NavView {
489                key: n.item.key.clone(),
490                label: i18n.t(&n.item.label),
491                path: nav::tab_path(n).unwrap_or_default().to_string(),
492                active: active_nav == Some(n.item.key.as_str()),
493                icon: icons::svg(&icon_set, &sprite_url, n.item.icon.as_deref()),
494            })
495            .collect();
496        let mut crumbs: Vec<CrumbView> = nav
497            .iter()
498            .filter(|n: &&NavView| n.active)
499            .map(|n| CrumbView {
500                label: n.label.clone(),
501                href: n.path.clone(),
502            })
503            .collect();
504        if let Some(entry) = sidebar
505            .iter()
506            .flat_map(|g| g.items.iter())
507            .find(|i| i.active)
508        {
509            crumbs.push(CrumbView {
510                label: entry.label.clone(),
511                href: entry.path.clone(),
512            });
513        }
514        Shell {
515            asset_urls,
516            icon_set,
517            sprite_url,
518            site_url,
519            base: base.to_string(),
520            brand,
521            nav,
522            crumbs,
523            full_name,
524            initial,
525            tz: resolve_display_tz(user.user.timezone.as_deref(), default_tz),
526            i18n,
527            sidebar,
528            csrf_token,
529            flash,
530            assets: Vec::new(),
531        }
532    }
533
534    /// The site's own root, for the chrome's link out to the front of the site.
535    pub(crate) fn site_url(&self) -> &str {
536        &self.site_url
537    }
538
539    /// Inline SVG for a named icon, for chrome that is not a nav item.
540    /// Whether a top-level tab is active, so the drawer nests the section
541    /// entries under it; otherwise the drawer appends them after the tabs.
542    pub(crate) fn sidebar_anchored(&self) -> bool {
543        self.nav.iter().any(|n| n.active)
544    }
545
546    pub(crate) fn icon(&self, name: &str) -> String {
547        icons::svg(&self.icon_set, &self.sprite_url, Some(name))
548    }
549
550    /// The URL for a built-in asset, named by a digest of its bytes. Templates
551    /// call `{{ shell.asset("laterite.css") }}`. An unregistered key yields the
552    /// plain path, which still serves (revalidating rather than immutable) and
553    /// trips a debug assertion.
554    pub(crate) fn asset(&self, key: &str) -> String {
555        match self.asset_urls.get(key) {
556            Some(path) => format!("{}/assets/{path}", self.base),
557            None => {
558                debug_assert!(false, "asset key `{key}` is not registered");
559                format!("{}/assets/{key}", self.base)
560            }
561        }
562    }
563
564    /// Localizes a source string in this request's locale, falling back to the
565    /// source itself. Templates call `{{ shell.t("Save") }}`.
566    pub fn t(&self, source: &str) -> String {
567        self.i18n.t(&Text::dynamic(source))
568    }
569
570    /// Localizes a prebuilt message (a `t!`/`tn!` value, a descriptor label, a
571    /// flash) into this request's locale.
572    pub fn tt(&self, text: &Text) -> String {
573        self.i18n.t(text)
574    }
575
576    /// The request's translator, for a field type that localizes strings of its
577    /// own (a repeater's sub-field labels) rather than only the label it is given.
578    pub fn i18n(&self) -> &Translator {
579        &self.i18n
580    }
581
582    /// The active locale (most specific in the chain), for `<html lang>`.
583    pub fn locale(&self) -> &str {
584        self.i18n.locale()
585    }
586
587    /// The admin mount (`/admin`), for a link into the panel.
588    pub fn base(&self) -> &str {
589        &self.base
590    }
591
592    /// This session's request token, for a form a screen builds by hand: a
593    /// hidden field named `_csrf`, placed first when the form uploads a file.
594    /// An HTMX request carries it already.
595    pub fn csrf_token(&self) -> &str {
596        &self.csrf_token
597    }
598
599    /// A UTC timestamp as stored (RFC 3339), shown in this operator's timezone.
600    /// Text that does not parse is shown as it is.
601    pub fn datetime(&self, utc: &str) -> String {
602        match chrono::DateTime::parse_from_rfc3339(utc) {
603            Ok(at) => at
604                .with_timezone(&self.tz)
605                .format("%Y-%m-%d %H:%M")
606                .to_string(),
607            Err(_) => utc.to_string(),
608        }
609    }
610
611    /// Renders `body` as a page in the admin chrome, headed by `title`. The
612    /// body is a screen's own markup, built from its templates through
613    /// [`html::Markup::from_template`].
614    pub fn page(&self, title: &Text, body: html::Markup) -> Response {
615        render(PageTemplate {
616            title: self.tt(title),
617            body,
618            shell: self.clone(),
619        })
620    }
621
622    /// Localizes a source string with integer `{name}` arguments, for a template
623    /// (`{{ shell.tf("Page {n} of {m}", [("n", page), ("m", pages)]) }}`). Nested-`Text`
624    /// arguments are built in Rust with `t!` and rendered with `tt`.
625    pub fn tf(&self, source: &str, args: &[(&'static str, i64)]) -> String {
626        let mut text = Text::dynamic(source);
627        for (name, value) in args {
628            text = text.arg(*name, *value);
629        }
630        self.i18n.t(&text)
631    }
632
633    /// Like [`Shell::tf`], but with string `{name}` arguments, for a template
634    /// (`{{ shell.tfs("Signed in as {name}", [("name", user)]) }}`).
635    pub fn tfs(&self, source: &str, args: &[(&'static str, &str)]) -> String {
636        let mut text = Text::dynamic(source);
637        for (name, value) in args {
638            text = text.arg(*name, *value);
639        }
640        self.i18n.t(&text)
641    }
642
643    #[cfg(test)]
644    pub(crate) fn test() -> Self {
645        Shell {
646            asset_urls: Arc::new(asset_urls(&builtin_assets())),
647            icon_set: Arc::new(laterite_core::icons::IconSet::new()),
648            sprite_url: Arc::from("/admin/assets/icons.svg"),
649            site_url: "http://localhost".to_string(),
650            base: "/admin".to_string(),
651            brand: "Laterite".to_string(),
652            nav: Vec::new(),
653            full_name: "Test Operator".to_string(),
654            initial: "T".to_string(),
655            tz: Tz::UTC,
656            i18n: Translator::new("en"),
657            sidebar: Vec::new(),
658            crumbs: Vec::new(),
659            csrf_token: "test-csrf-token".to_string(),
660            flash: Vec::new(),
661            assets: Vec::new(),
662        }
663    }
664}
665
666/// Whether `path` sits in the settings context, and if so which item code is
667/// active. A screen is in the settings context when it is the settings index or
668/// a settings form, or when its path falls under a settings item's `link` (its
669/// list, forms and sub-pages). The matching item is returned so the sidebar can
670/// highlight it. `visible` is the operator's permitted items, so a linked
671/// resource they cannot see never claims the context.
672fn settings_context(
673    visible: &[settings::SettingsItem],
674    admin_path: &str,
675    path: &str,
676) -> (bool, Option<String>) {
677    if path == format!("{admin_path}/settings") {
678        return (true, None);
679    }
680    // A settings screen mounts in its module's namespace, not under /settings,
681    // so the context is found by matching the resolved paths rather than by
682    // stripping a prefix. A linked item (a resource in the settings menu) owns
683    // the context across its sub-pages, so /admin/roles/5/edit still resolves;
684    // the longest match wins.
685    let own = visible
686        .iter()
687        .filter(|i| i.link.is_none())
688        .find(|i| path == format!("{admin_path}{}", i.route()))
689        .map(|i| i.code.clone());
690    if own.is_some() {
691        return (true, own);
692    }
693    let linked = visible
694        .iter()
695        .filter_map(|i| {
696            i.link
697                .as_deref()
698                .map(|link| (format!("{admin_path}{link}"), &i.code))
699        })
700        .filter(|(link, _)| path == link.as_str() || path.starts_with(&format!("{link}/")))
701        .max_by_key(|(link, _)| link.len())
702        .map(|(_, code)| code.clone());
703    (linked.is_some(), linked)
704}
705
706/// Resolves the per-request navigation context: the menu as this operator sees
707/// it, the key of the tab `path` falls under, and the context sidebar (the
708/// settings categories inside the settings context, else the active section's
709/// entries). The auth guard runs this once per request and hands all three to
710/// the [`Shell`].
711#[allow(clippy::too_many_arguments)]
712fn resolve_nav_context(
713    nav: &nav::NavTree,
714    items: &[settings::SettingsItem],
715    admin_path: &str,
716    perms: &PermissionSet,
717    own_order: Option<&str>,
718    path: &str,
719    tr: &Translator,
720    icons: icons::Icons<'_>,
721) -> (
722    Vec<nav::NavNode>,
723    Vec<settings::CategoryView>,
724    Option<String>,
725) {
726    let mut visible_nav = nav.visible(&|code| perms.allows(code));
727    if let Some(order) = own_order {
728        nav::apply_order(&mut visible_nav, order);
729    }
730    // A per-operator item lives on the Preferences page, not in Settings.
731    let visible: Vec<settings::SettingsItem> = visible_settings(items, perms)
732        .into_iter()
733        .filter(|i| !i.per_operator)
734        .collect();
735    let (in_context, active) = settings_context(&visible, admin_path, path);
736    if in_context {
737        let sidebar = settings::sidebar_groups(&visible, admin_path, active.as_deref(), tr, icons);
738        return (visible_nav, sidebar, Some("settings".to_string()));
739    }
740    let active_top = nav::active_top(&visible_nav, admin_path, path);
741    let sidebar = active_top
742        .map(|node| nav::section_sidebar(node, admin_path, path, tr, icons))
743        .unwrap_or_default();
744    let active_key = active_top.map(|node| node.item.key.clone());
745    (visible_nav, sidebar, active_key)
746}
747
748/// Resolves the timezone an operator's timestamps render in: their own
749/// preference when it is set and a valid IANA name, otherwise the deployment
750/// default. An unparseable stored value falls back rather than erroring.
751fn resolve_display_tz(preference: Option<&str>, default_tz: Tz) -> Tz {
752    preference
753        .and_then(|name| name.parse::<Tz>().ok())
754        .unwrap_or(default_tz)
755}
756
757/// Whether a timezone is offered in the picker's zone list.
758fn zone_offered(name: &str) -> bool {
759    !matches!(name, "Asia/Jerusalem" | "Asia/Tel_Aviv")
760}
761
762/// The base language of a tag (`kn-IN` -> `kn`), lowercased. Catalogs are keyed by
763/// base language.
764fn base_lang(tag: &str) -> String {
765    tag.split(['-', '_'])
766        .next()
767        .unwrap_or(tag)
768        .to_ascii_lowercase()
769}
770
771/// Whether resolution can serve `base`: English (the source, always reachable), a
772/// locale with a loaded catalog, or the QA pseudo-locale (selectable via config or
773/// `Accept-Language`, though never shown in the picker). The serveable set is the
774/// deployment's loaded catalogs, so shipping a `de.po` makes `de` resolve with no
775/// code change.
776fn is_serveable(base: &str, serveable: &[String]) -> bool {
777    base == "en" || base == laterite_core::PSEUDO_LOCALE || serveable.iter().any(|l| l == base)
778}
779
780/// The deployment default locale from config, normalized to a base tag the running
781/// catalogs can serve, else `en`.
782fn default_locale(configured: &str, serveable: &[String]) -> String {
783    let base = base_lang(configured);
784    if is_serveable(&base, serveable) {
785        base
786    } else {
787        "en".to_string()
788    }
789}
790
791/// The locales the language picker offers: English (the source, always) then every
792/// locale with a loaded catalog, sorted. The pseudo-locale is resolvable but never
793/// offered here.
794fn offered_locales(catalogs: &CatalogStore) -> Vec<String> {
795    let mut out = vec!["en".to_string()];
796    out.extend(catalogs.locales());
797    out
798}
799
800/// A locale's display name for the picker. The framework names only its own source
801/// language (English); every other locale shows by its tag. A locale's own name
802/// (endonym) is data that belongs with the catalog that provides the locale, not a
803/// table of specific languages the framework would otherwise have to hold for all.
804fn locale_name(code: &str) -> String {
805    if code == "en" {
806        "English".to_string()
807    } else {
808        code.to_string()
809    }
810}
811
812/// The tags in an `Accept-Language` header, most-preferred first. Each entry's
813/// optional `;q=` weight orders them (absent means `1.0`); `*` is dropped.
814fn parse_accept_language(header: &str) -> Vec<String> {
815    let mut items: Vec<(f32, String)> = header
816        .split(',')
817        .filter_map(|part| {
818            let mut bits = part.split(';');
819            let tag = bits.next()?.trim();
820            if tag.is_empty() || tag == "*" {
821                return None;
822            }
823            let q = bits
824                .find_map(|p| p.trim().strip_prefix("q="))
825                .and_then(|q| q.parse::<f32>().ok())
826                .unwrap_or(1.0);
827            Some((q, tag.to_string()))
828        })
829        .collect();
830    // Stable sort by weight descending, so equal weights keep header order.
831    items.sort_by(|a, b| b.0.total_cmp(&a.0));
832    items.into_iter().map(|(_, tag)| tag).collect()
833}
834
835/// Builds this request's locale fallback chain, most specific first and always
836/// ending at `en`. Candidates, in order: the operator's stored locale, the
837/// `Accept-Language` tags, the deployment default. Each is normalized to a base
838/// language the running catalogs can serve; unserveable tags are skipped and none
839/// repeats.
840fn resolve_locale_chain(
841    preference: Option<&str>,
842    accept_language: Option<&str>,
843    default: &str,
844    serveable: &[String],
845) -> Vec<String> {
846    let mut chain: Vec<String> = Vec::new();
847    let consider = |tag: &str, chain: &mut Vec<String>| {
848        let base = base_lang(tag);
849        if is_serveable(&base, serveable) && !chain.contains(&base) {
850            chain.push(base);
851        }
852    };
853    if let Some(pref) = preference {
854        consider(pref, &mut chain);
855    }
856    if let Some(header) = accept_language {
857        for tag in parse_accept_language(header) {
858            consider(&tag, &mut chain);
859        }
860    }
861    consider(default, &mut chain);
862    // Guarantee the source language is reachable, appended only if not already
863    // signaled earlier (so an explicit en preference keeps its position).
864    consider("en", &mut chain);
865    chain
866}
867
868/// A translator for a pre-auth screen (login, setup): no operator preference exists
869/// yet, so the chain is the request's `Accept-Language`, then the deployment default,
870/// then `en`, over the shared catalogs.
871fn pre_auth_translator(state: &AdminState, headers: &HeaderMap) -> Translator {
872    let accept = headers.get("accept-language").and_then(|v| v.to_str().ok());
873    let serveable = state.catalogs.locales();
874    let chain = resolve_locale_chain(None, accept, &state.default_locale, &serveable);
875    Translator::with_chain(chain, state.catalogs.clone())
876}
877
878/// An admin resource: a list screen, optionally with a create/edit form, mounted
879/// under `base_path` and shown in the menu as `nav_label`.
880///
881/// Built with [`Resource::new`] plus its builder methods. Non-exhaustive because
882/// this is the descriptor a plugin author writes and the one most likely to grow:
883/// a struct literal outside this crate would freeze its field set at 1.0, so the
884/// framework could never learn anything new about a resource.
885#[derive(Serialize)]
886#[non_exhaustive]
887pub struct Resource {
888    /// The path the resource mounts at, relative to the admin root and starting
889    /// with a slash (e.g. `/products`). The framework prepends the configured
890    /// admin mount, so a resource never hardcodes it and survives a moved panel.
891    /// The list's `edit_base` and the form's `base_path` are resolved the same
892    /// way.
893    pub base_path: String,
894    /// The menu label, localized at render. Serde stays a plain string.
895    pub nav_label: Text,
896    pub list: list::ListConfig,
897    pub form: Option<form::FormConfig>,
898    /// The permission an operator must hold to reach any of the resource's
899    /// routes. A dotted string gates every route the resource mounts, and an
900    /// operator who lacks it receives `403 Forbidden`; superusers pass regardless.
901    /// `None` leaves the resource open to any signed-in operator and is allowed
902    /// only for a read-only resource: a resource with a create/edit `form` must
903    /// declare a permission, or boot aborts (see [`mount_resource`]).
904    pub permission: Option<String>,
905    /// Whether records may be imported into this resource, and by whom. The
906    /// pages mount under the resource's path; see [`import`].
907    pub import: Option<ImportConfig>,
908    /// The picker source the command palette finds this resource's records
909    /// through, leading to their edit pages. `None` keeps them out of it.
910    pub palette: Option<String>,
911    /// Other entities' records that belong to each of this resource's records,
912    /// each a section on the edit page. See [`relation::RelationConfig`].
913    pub relations: Vec<relation::RelationConfig>,
914    /// Where the menu entry sits: under a section, with an icon, at a
915    /// position; or out of the menu. See [`nav::Placement`].
916    pub menu: nav::Placement,
917}
918
919/// What a resource declares when records may be imported into it: `import:
920/// true` in a descriptor file, or a map with the keys below.
921#[derive(Clone, Debug, Default, Serialize, Deserialize)]
922#[non_exhaustive]
923pub struct ImportConfig {
924    /// The permission an operator needs to import. `None` asks for the
925    /// resource's own.
926    #[serde(default)]
927    pub permission: Option<String>,
928}
929
930impl ImportConfig {
931    pub fn new() -> Self {
932        Self::default()
933    }
934
935    /// The permission an operator needs to import, when it is not the
936    /// resource's own.
937    pub fn permission(mut self, code: impl Into<String>) -> Self {
938        self.permission = Some(code.into());
939        self
940    }
941}
942
943/// A permission an operator can be granted: a dotted `code`, a human `label`,
944/// and a `group` heading it sorts under in the role editor. The framework
945/// registers its own (see the built-in grants), and an application registers
946/// its permissions through [`router`] so they appear in the editor alongside.
947#[derive(Clone, Serialize)]
948#[non_exhaustive]
949pub struct Permission {
950    pub code: String,
951    /// The permission's display label and group heading, localized at render.
952    pub label: Text,
953    pub group: Text,
954    /// The built-in roles that hold this permission. Empty means
955    /// [`ROLE_ADMIN`] alone.
956    pub default_roles: Vec<String>,
957    /// Codes this permission used to have. At boot every role and override
958    /// still holding one is rewritten to the current code.
959    pub renamed_from: Vec<String>,
960}
961
962pub use laterite_auth::{ROLE_ADMIN, ROLE_EDITOR};
963
964impl Permission {
965    /// A permission an operator can be granted, held by [`ROLE_ADMIN`] until it
966    /// names other roles with [`Permission::roles`].
967    pub fn new(code: impl Into<String>, label: impl Into<Text>, group: impl Into<Text>) -> Self {
968        Self {
969            code: code.into(),
970            label: label.into(),
971            group: group.into(),
972            default_roles: Vec::new(),
973            renamed_from: Vec::new(),
974        }
975    }
976
977    /// Codes this permission used to have.
978    ///
979    /// A role or override still holding one is rewritten at the next boot, so a
980    /// rename repairs what operators saved rather than leaving them granting a
981    /// string nothing checks.
982    pub fn renamed_from<I, S>(mut self, codes: I) -> Self
983    where
984        I: IntoIterator<Item = S>,
985        S: Into<String>,
986    {
987        self.renamed_from = codes.into_iter().map(Into::into).collect();
988        self
989    }
990
991    /// The built-in roles that hold this permission by default. Naming
992    /// [`ROLE_EDITOR`] alone keeps it out of [`ROLE_ADMIN`].
993    pub fn roles<I, S>(mut self, roles: I) -> Self
994    where
995        I: IntoIterator<Item = S>,
996        S: Into<String>,
997    {
998        self.default_roles = roles.into_iter().map(Into::into).collect();
999        self
1000    }
1001}
1002
1003/// Every rename the registry declares, as `(old, new)` pairs.
1004///
1005/// Two permissions claiming one old code cannot both be right, and silently
1006/// picking one would move an operator's grant to the wrong place, so it aborts
1007/// the boot naming both.
1008pub fn permission_renames(contributed: &[Permission]) -> Vec<(String, String)> {
1009    let permissions: Vec<Permission> = builtin_permissions()
1010        .into_iter()
1011        .chain(contributed.iter().cloned())
1012        .collect();
1013    let mut out: Vec<(String, String)> = Vec::new();
1014    for permission in &permissions {
1015        for old in &permission.renamed_from {
1016            if let Some((_, taken)) = out.iter().find(|(o, _)| o == old) {
1017                panic!(
1018                    "permissions `{taken}` and `{}` both claim the old code `{old}`",
1019                    permission.code
1020                );
1021            }
1022            if permissions.iter().any(|p| &p.code == old) {
1023                panic!(
1024                    "permission `{}` claims `{old}` as an old code, but `{old}` is still registered",
1025                    permission.code
1026                );
1027            }
1028            out.push((old.clone(), permission.code.clone()));
1029        }
1030    }
1031    out
1032}
1033
1034/// The framework's roles, with the permissions the registry says they hold.
1035///
1036/// A permission that names no role belongs to [`ROLE_ADMIN`] alone: an
1037/// undeclared permission reaching only the administrator is the safe reading,
1038/// and the role editor shows the author it is not reaching editors.
1039pub fn system_roles(contributed: &[Permission]) -> Vec<laterite_auth::store::SystemRole<'static>> {
1040    // The framework's own permissions belong in its own roles, and `router` adds
1041    // them after this runs, so take them from the same source it does.
1042    let permissions: Vec<Permission> = builtin_permissions()
1043        .into_iter()
1044        .chain(contributed.iter().cloned())
1045        .collect();
1046    let held = |role: &str| -> Vec<String> {
1047        permissions
1048            .iter()
1049            .filter(|p| {
1050                if p.default_roles.is_empty() {
1051                    role == ROLE_ADMIN
1052                } else {
1053                    p.default_roles.iter().any(|r| r == role)
1054                }
1055            })
1056            .map(|p| p.code.clone())
1057            .collect()
1058    };
1059    vec![
1060        laterite_auth::store::SystemRole {
1061            code: ROLE_ADMIN,
1062            name: "Administrator",
1063            description: "Administers the panel itself: operators, roles and settings.",
1064            permissions: held(ROLE_ADMIN),
1065        },
1066        laterite_auth::store::SystemRole {
1067            code: ROLE_EDITOR,
1068            name: "Editor",
1069            description: "Works with the content the application declares.",
1070            permissions: held(ROLE_EDITOR),
1071        },
1072    ]
1073}
1074
1075impl Resource {
1076    /// A read-only resource: a list at `base_path`, in the menu as `nav_label`.
1077    ///
1078    /// A create/edit form is added with [`Resource::form`], which also requires
1079    /// [`Resource::permission`]: an unguarded write resource aborts boot.
1080    pub fn new(
1081        base_path: impl Into<String>,
1082        nav_label: impl Into<Text>,
1083        list: list::ListConfig,
1084    ) -> Self {
1085        Self {
1086            base_path: base_path.into(),
1087            nav_label: nav_label.into(),
1088            list,
1089            form: None,
1090            permission: None,
1091            import: None,
1092            palette: None,
1093            relations: Vec::new(),
1094            menu: nav::Placement::default(),
1095        }
1096    }
1097
1098    /// Lets the command palette find this resource's records through the
1099    /// picker source named, opening each at its edit page.
1100    pub fn palette(mut self, source: impl Into<String>) -> Self {
1101        self.palette = Some(source.into());
1102        self
1103    }
1104
1105    /// Where the menu entry sits. See [`nav::Placement`].
1106    pub fn menu(mut self, placement: nav::Placement) -> Self {
1107        self.menu = placement;
1108        self
1109    }
1110
1111    /// Adds a section of related records to the edit page. Needs a form.
1112    pub fn relation(mut self, relation: relation::RelationConfig) -> Self {
1113        self.relations.push(relation);
1114        self
1115    }
1116
1117    /// Lets records be imported into this resource, which needs a form.
1118    pub fn import(mut self, import: ImportConfig) -> Self {
1119        self.import = Some(import);
1120        self
1121    }
1122
1123    /// Adds the create/edit form. A resource with one must also declare a
1124    /// permission, or boot aborts.
1125    pub fn form(mut self, form: form::FormConfig) -> Self {
1126        self.form = Some(form);
1127        self
1128    }
1129
1130    /// The permission gating every route this resource mounts.
1131    pub fn permission(mut self, permission: impl Into<String>) -> Self {
1132        self.permission = Some(permission.into());
1133        self
1134    }
1135}
1136
1137/// Refuses deletion of a role the framework owns.
1138///
1139/// The row would return at the next boot, but `backend_user_roles` cascades, so
1140/// every operator's assignment to it would be gone for good. The edit screen
1141/// already refuses; this closes the list's Delete.
1142struct SystemRoleGuard;
1143
1144#[laterite_core::strata::async_trait]
1145impl laterite_core::ModelListener for SystemRoleGuard {
1146    async fn before_delete(
1147        &self,
1148        cx: &mut laterite_core::SaveCx<'_>,
1149        rec: &laterite_core::Record,
1150    ) -> Result<(), Text> {
1151        let Some(id) = rec.id() else {
1152            return Ok(());
1153        };
1154        // Read on the delete's own connection, so it sees the transaction's state.
1155        let backend = cx.backend();
1156        match laterite_auth::store::role_is_system_on(cx.conn(), backend, id).await {
1157            Ok(true) => Err(t!(
1158                "The framework maintains this role; it cannot be deleted."
1159            )),
1160            // A read that failed is not a licence to delete.
1161            Err(_) => Err(t!(
1162                "Could not check whether this role is maintained by the framework."
1163            )),
1164            Ok(false) => Ok(()),
1165        }
1166    }
1167}
1168
1169/// The framework's own permissions, offered in the role editor under a
1170/// "Backend" group. These gate the built-in Users and Roles screens.
1171fn builtin_permissions() -> Vec<Permission> {
1172    // Each names no role, so each belongs to the administrator alone: every one
1173    // of them administers the panel rather than its content.
1174    vec![
1175        Permission::new("backend.manage_users", "Manage backend users", "Backend"),
1176        Permission::new("backend.manage_roles", "Manage roles", "Backend"),
1177        Permission::new("backend.manage_branding", "Manage branding", "Backend"),
1178        Permission::new(plugins::MANAGE_PERMISSION, "Manage plugins", "Backend"),
1179        Permission::new("backend.view_audit_log", "View the audit log", "Backend"),
1180        Permission::new("backend.view_access_log", "View the access log", "Backend"),
1181        Permission::new(
1182            "backend.view_request_log",
1183            "View the request log",
1184            "Backend",
1185        ),
1186    ]
1187}
1188
1189/// Every source string in the framework's built-in admin descriptors: resource nav
1190/// labels and their list titles and column headers, settings items and their fields,
1191/// and permission labels and groups. `lat i18n extract` folds these into the admin
1192/// catalog. Collected through the serde source walk, so it never drifts as new label
1193/// fields are added.
1194pub fn descriptor_sources() -> Vec<String> {
1195    let mut out = Vec::new();
1196    out.extend(laterite_core::collect_sources(&builtin_resources()));
1197    out.extend(laterite_core::collect_sources(&builtin_settings()));
1198    out.extend(laterite_core::collect_sources(&builtin_permissions()));
1199    out.sort();
1200    out.dedup();
1201    out
1202}
1203
1204/// The migration sets for every module the admin mounts: the auth schema
1205/// (users, roles, sessions, access log) and the settings store. Run these
1206/// before serving [`router`] so its built-in screens have their tables, so an
1207/// application never has to know which framework modules the admin pulls in.
1208///
1209/// An application with its own modules appends their sets:
1210///
1211/// ```no_run
1212/// # async fn f(db: laterite_core::Db) -> Result<(), Box<dyn std::error::Error>> {
1213/// let mut migrations = laterite_admin::builtin_migrations();
1214/// // migrations.extend([my_module::migrations()]);
1215/// laterite_core::migration::run(&db.pool, db.backend, &migrations).await?;
1216/// # Ok(()) }
1217/// ```
1218pub fn builtin_migrations() -> Vec<laterite_core::MigrationSet> {
1219    builtin_modules().iter().map(|m| m.migrations()).collect()
1220}
1221
1222/// The framework's built-in modules, in registration order. `Bootstrap`
1223/// registers these before an app's own modules, so the admin's tables migrate
1224/// first.
1225pub fn builtin_modules() -> Vec<Box<dyn laterite_core::Module>> {
1226    vec![
1227        Box::new(laterite_auth::AuthModule),
1228        Box::new(settings::SettingsModule),
1229        Box::new(requestlog::RequestLogModule),
1230        Box::new(plugins::PluginsModule),
1231        Box::new(laterite_media::MediaModule),
1232        Box::new(import::ImportModule),
1233    ]
1234}
1235
1236/// Builds the admin router. `app_resources` are the application's own list/form
1237/// screens; `app_settings` are its settings models; `app_permissions` are the
1238/// permissions it defines, offered in the role editor alongside the framework's.
1239/// All are mounted alongside the framework's built-in equivalents.
1240/// Everything the modules and the application contribute to the admin, in one
1241/// value.
1242///
1243/// Build it with the fields you mean and leave the rest to `Default`:
1244///
1245/// ```
1246/// # use laterite_admin::Contributions;
1247/// let contributions = Contributions {
1248///     permissions: Vec::new(),
1249///     ..Default::default()
1250/// };
1251/// ```
1252///
1253/// It exists so that a new kind of contribution is a new field rather than a new
1254/// argument. The nine of them were positional before, and a run of interchangeable
1255/// `Vec::new()` placeholders is a mistake the compiler cannot catch: swap two and
1256/// it still builds. Naming them removes that whole class of error, and ending a
1257/// literal with `..Default::default()` means a later field does not break the
1258/// call.
1259#[derive(Default)]
1260pub struct Contributions {
1261    /// List and form screens, mounted beside the framework's own.
1262    pub resources: Vec<Resource>,
1263    /// Settings models, offered in the settings area.
1264    pub settings: Vec<settings::SettingsItem>,
1265    /// Permissions defined by the application, offered in the role editor.
1266    pub permissions: Vec<Permission>,
1267    /// Sources a reference field searches and resolves against.
1268    pub picker_sources: Vec<picker::PickerSourceReg>,
1269    /// Named write handlers a form can select.
1270    pub persisters: Vec<persist::PersisterReg>,
1271    /// Listeners run around every save and delete.
1272    pub listeners: Vec<laterite_core::ModelListenerReg>,
1273    /// Column types a list cell can render through.
1274    /// Field types a module contributes, offered to every form and settings
1275    /// screen beside the built-ins.
1276    pub field_types: Vec<field::FieldTypeReg>,
1277    pub column_types: Vec<list::ColumnTypeReg>,
1278    /// Icons a module contributes, for glyphs the framework's curated set does
1279    /// not carry. Each is namespaced to the contributing module.
1280    pub icons: Vec<(laterite_core::ModuleId, laterite_core::icons::IconReg)>,
1281    /// Screens a module mounts itself, for anything that is not a list or form.
1282    pub screens: Vec<routes::ScreenReg>,
1283    /// Routes mounted outside the admin, at literal paths.
1284    pub public_routes: Vec<routes::PublicRouteReg>,
1285    /// Menu entries and sections beyond what resources and screens add for
1286    /// themselves. See [`nav::NavItem`].
1287    pub nav: Vec<nav::NavItem>,
1288    /// Changes to other modules' resources, applied before they mount. See
1289    /// [`ResourceHook`].
1290    pub resource_hooks: Vec<ResourceHook>,
1291    /// Everything the framework itself does not consume: the contribution types
1292    /// modules define for each other. Kept whole so a contributed route can read
1293    /// them through [`routes::RouteCtx::contributions`], which is what makes a
1294    /// module's own extension point usable by another module.
1295    pub plugin_defined: Arc<laterite_core::Registry>,
1296}
1297
1298pub fn router(
1299    auth: AuthService,
1300    db: Db,
1301    contributions: Contributions,
1302    config: AdminConfig,
1303    catalogs: Arc<CatalogStore>,
1304) -> Router {
1305    let Contributions {
1306        resources: app_resources,
1307        settings: app_settings,
1308        permissions: app_permissions,
1309        picker_sources: app_picker_sources,
1310        persisters: app_persisters,
1311        listeners: app_listeners,
1312        field_types: app_field_types,
1313        column_types: app_column_types,
1314        icons: app_icons,
1315        screens: app_screens,
1316        public_routes: app_public,
1317        nav: app_nav,
1318        resource_hooks,
1319        plugin_defined,
1320    } = contributions;
1321    let admin_path = normalize_path(&config.path);
1322
1323    let mut resources = builtin_resources();
1324    let mut app_resources = app_resources;
1325    // Another module's changes to a resource, before anything reads it. A hook
1326    // naming no resource is a wiring bug, so it aborts boot.
1327    for hook in resource_hooks {
1328        let found = resources
1329            .iter_mut()
1330            .chain(app_resources.iter_mut())
1331            .find(|r| r.base_path == hook.target);
1332        match found {
1333            Some(resource) => {
1334                let changed = hook.apply(std::mem::replace(
1335                    resource,
1336                    Resource::new("", "", list::ListConfig::default()),
1337                ));
1338                *resource = changed;
1339            }
1340            None => panic!(
1341                "a resource hook targets `{}`, which no module declared",
1342                hook.target
1343            ),
1344        }
1345    }
1346    // Descriptor paths are authored relative to the admin root; resolve them to
1347    // full paths under the configured mount so routes, the menu, and every link
1348    // built from them agree.
1349    for resource in resources.iter_mut().chain(app_resources.iter_mut()) {
1350        prefix_resource(&admin_path, resource);
1351    }
1352    // A resource that may be imported into shows the way to its import pages. A
1353    // write path, so it is gated: the key's permission, else the resource's,
1354    // and a resource with neither aborts boot like an unguarded form.
1355    for resource in app_resources.iter_mut() {
1356        if let Some(import) = &resource.import {
1357            let permission = import
1358                .permission
1359                .clone()
1360                .or_else(|| resource.permission.clone())
1361                .unwrap_or_else(|| {
1362                    panic!(
1363                        "admin resource `{}` declares `import` but no permission; importing \
1364                         writes records, so it must be gated",
1365                        resource.base_path
1366                    )
1367                });
1368            resource.list.import = Some(routes::feature_link(
1369                &resource.base_path,
1370                "import",
1371                &permission,
1372            ));
1373        }
1374    }
1375
1376    let mut settings = builtin_settings();
1377    settings.extend(app_settings);
1378    // The framework's own listeners run before the modules', so a contributed
1379    // one can see what they decided.
1380    let mut app_listeners = app_listeners;
1381    app_listeners.insert(
1382        0,
1383        laterite_core::ModelListenerReg::for_entity("backend_roles", Arc::new(SystemRoleGuard)),
1384    );
1385
1386    let mut permissions = builtin_permissions();
1387    permissions.extend(app_permissions);
1388    // The codes a column may require; `list::check` refuses one nobody registered.
1389    let permission_codes: std::collections::HashSet<String> =
1390        permissions.iter().map(|p| p.code.clone()).collect();
1391
1392    // The menu: Dashboard first and Settings last, the application's sections
1393    // and entries between, each entry carrying its target's permission so the
1394    // tree filters itself per operator. Built-in Users and Roles are settings
1395    // items (see the settings menu), not tabs. A resource's path is under the
1396    // admin mount already; a contributed item's and a screen's are not.
1397    let mut nav_items = vec![
1398        nav::NavItem::new("dashboard", "Dashboard", "")
1399            .icon("layout-dashboard")
1400            .order(i32::MIN),
1401        nav::NavItem::new("settings", "Settings", "/settings")
1402            .icon("settings")
1403            .order(i32::MAX),
1404    ];
1405    nav_items.extend(app_nav);
1406    for resource in &app_resources {
1407        if resource.menu.hidden {
1408            continue;
1409        }
1410        let unprefixed = resource
1411            .base_path
1412            .strip_prefix(admin_path.as_str())
1413            .unwrap_or(&resource.base_path)
1414            .to_string();
1415        let mut item = nav::NavItem::new(
1416            format!("resource:{unprefixed}"),
1417            resource.nav_label.clone(),
1418            unprefixed,
1419        )
1420        .order(resource.menu.order);
1421        item.icon = resource.menu.icon.clone();
1422        item.permission = resource.permission.clone();
1423        item.under = resource.menu.under.clone();
1424        item.after = resource.menu.after.clone();
1425        item.before = resource.menu.before.clone();
1426        nav_items.push(item);
1427    }
1428    for reg in &app_screens {
1429        let Some(label) = &reg.nav_label else {
1430            continue;
1431        };
1432        if reg.menu.hidden {
1433            continue;
1434        }
1435        let mut item = nav::NavItem::new(
1436            format!("screen:{}", reg.base_path),
1437            label.clone(),
1438            reg.base_path.clone(),
1439        )
1440        .permission(reg.permission.clone())
1441        .order(reg.menu.order);
1442        item.icon = reg.menu.icon.clone();
1443        item.under = reg.menu.under.clone();
1444        item.after = reg.menu.after.clone();
1445        item.before = reg.menu.before.clone();
1446        nav_items.push(item);
1447    }
1448    let nav =
1449        nav::NavTree::build(nav_items, &admin_path).unwrap_or_else(|e| panic!("admin menu: {e}"));
1450    // The palette's record sources: a resource that named its picker source.
1451    // The source itself is checked against the registry below, once it exists.
1452    let palette_sources: Vec<palette::RecordSource> = app_resources
1453        .iter()
1454        .filter_map(|r| {
1455            r.palette.as_ref().map(|source| palette::RecordSource {
1456                label: r.nav_label.clone(),
1457                source: source.clone(),
1458                base_path: r.base_path.clone(),
1459                permission: r.permission.clone(),
1460            })
1461        })
1462        .collect();
1463    resources.extend(app_resources);
1464
1465    let app_name = if config.app_name.trim().is_empty() {
1466        "Laterite".to_string()
1467    } else {
1468        config.app_name.clone()
1469    };
1470
1471    // The picker-source registry, keyed by dotted name. A bad name or a duplicate
1472    // is a wiring bug, so it aborts boot.
1473    let mut pickers = picker::PickerRegistry::new();
1474    for reg in app_picker_sources {
1475        let name = reg.name.clone();
1476        if !field::is_name(&name, true) {
1477            panic!("invalid picker source name `{name}`");
1478        }
1479        if pickers.insert(name.clone(), reg).is_some() {
1480            panic!("duplicate picker source `{name}`");
1481        }
1482    }
1483
1484    // The reference field validates its `source` against the picker registry at
1485    // boot, so build the field registry here (over the arg-free built-ins) with
1486    // the picker field added and the registry injected.
1487    for source in &palette_sources {
1488        if !pickers.contains_key(&source.source) {
1489            panic!(
1490                "admin resource `{}` names palette source `{}`, which no module registered",
1491                source.base_path, source.source
1492            );
1493        }
1494    }
1495    let pickers = Arc::new(pickers);
1496    let mut field_types = field::builtin_registry();
1497    field_types.insert(
1498        "reference".to_string(),
1499        Arc::new(field::RefPickerField::new(pickers.clone())),
1500    );
1501
1502    // The form-persister registry: a bad or duplicate name is a wiring bug, so it
1503    // aborts boot. It is not on AdminState; `prepare` resolves it per form.
1504    let mut persisters = persist::PersisterRegistry::new();
1505    for reg in app_persisters {
1506        let name = reg.name.clone();
1507        if !field::is_name(&name, true) {
1508            panic!("invalid persister name `{name}`");
1509        }
1510        if persisters.insert(name.clone(), reg.persister).is_some() {
1511            panic!("duplicate persister `{name}`");
1512        }
1513    }
1514
1515    // Module-contributed field types join the registry built above, rather than a
1516    // fresh one: rebuilding here would drop the reference field that was just
1517    // inserted, since that one needs the picker registry and cannot come from the
1518    // arg-free built-ins. A module can offer an input the framework has none of,
1519    // which is what keeps a custom input from meaning a framework change.
1520    for reg in app_field_types {
1521        let name = reg.name().to_string();
1522        if !field::is_name(&name, true) {
1523            panic!("invalid field type name `{name}`");
1524        }
1525        if field_types.insert(name.clone(), reg.field_type).is_some() {
1526            panic!("duplicate field type `{name}`");
1527        }
1528    }
1529
1530    // The icon set: the framework's curated names, plus whatever modules
1531    // contributed. A bad name or unusable SVG aborts the boot rather than
1532    // rendering something wrong later.
1533    let mut icon_set = laterite_core::icons::IconSet::new();
1534    for (owner, reg) in app_icons {
1535        if let Err(e) = icon_set.add(owner.as_str(), &reg) {
1536            panic!("module `{owner}` contributed an invalid icon: {e}");
1537        }
1538    }
1539
1540    // The sprite joins the asset registry, so it gets a content-named URL and
1541    // may be cached forever: a changed set is a changed URL.
1542    let mut assets = builtin_assets();
1543    assets.insert(
1544        ICON_SPRITE,
1545        AdminAsset {
1546            mime: "image/svg+xml",
1547            bytes: std::borrow::Cow::Owned(icon_set.sprite().into_bytes()),
1548        },
1549    );
1550
1551    // Every descriptor icon is checked now, while the names are all in hand and
1552    // nobody is waiting on a response. A typo here used to reach production as a
1553    // wrong picture that looked like somebody's choice.
1554    for item in &settings {
1555        icons::require(
1556            &icon_set,
1557            &format!("settings item `{}`", item.code),
1558            item.icon.as_deref(),
1559        );
1560    }
1561    for node in nav
1562        .top
1563        .iter()
1564        .flat_map(|n| std::iter::once(n).chain(n.children.iter()))
1565    {
1566        icons::require(
1567            &icon_set,
1568            &format!("menu entry `{}`", node.item.key),
1569            node.item.icon.as_deref(),
1570        );
1571    }
1572
1573    // The column-type registry: the built-ins, plus whatever the modules
1574    // contributed. A bad or duplicate key is a wiring bug, so it aborts boot the
1575    // way a duplicate persister or picker source does.
1576    let mut column_types = list::builtin_column_registry();
1577    for reg in app_column_types {
1578        let name = reg.name().to_string();
1579        if !field::is_name(&name, true) {
1580            panic!("invalid column type name `{name}`");
1581        }
1582        if column_types.insert(name.clone(), reg.column_type).is_some() {
1583            panic!("duplicate column type `{name}`");
1584        }
1585    }
1586
1587    let settings = Arc::new(settings);
1588    // One render of the asset URLs, shared by the state and the sprite lookup.
1589    let asset_urls_arc = Arc::new(asset_urls(&assets));
1590    let sprite_url: Arc<str> = Arc::from(
1591        asset_urls_arc
1592            .get(ICON_SPRITE)
1593            .map(|p| format!("{admin_path}/assets/{p}"))
1594            .unwrap_or_default()
1595            .as_str(),
1596    );
1597    let icons_arc = Arc::new(icon_set);
1598    let state = AdminState {
1599        auth,
1600        db,
1601        nav: Arc::new(nav),
1602        settings: settings.clone(),
1603        permissions: Arc::new(permissions),
1604        admin_path: Arc::from(admin_path.as_str()),
1605        secure_cookie: config.secure_cookie,
1606        trusted_proxies: Arc::new(clientip::parse_trusted(&config.trusted_proxies)),
1607        icons: icons_arc.clone(),
1608        sprite_url: sprite_url.clone(),
1609        origin: Arc::from(config.origin.trim_end_matches('/')),
1610        timezone: config.timezone.parse().unwrap_or(Tz::UTC),
1611        default_locale: Arc::from(default_locale(&config.locale, &catalogs.locales())),
1612        catalogs,
1613        app_name,
1614        brand_cache: Arc::new(RwLock::new(None)),
1615        field_types: Arc::new(field_types),
1616        column_types: Arc::new(column_types),
1617        plugin_defined,
1618        assets: Arc::new(assets),
1619        asset_urls: asset_urls_arc.clone(),
1620        pickers,
1621        palette: Arc::new(palette_sources),
1622        overrides: Arc::new(field::NoOverrides),
1623    };
1624
1625    let mut protected = Router::new().route(&admin_path, get(dashboard));
1626    // The resources' forms, collected as they mount so a screen can write
1627    // through one (`RouteCtx::form`). Keyed by the path as authored, relative to
1628    // the admin root, which is how a screen names a resource.
1629    let mut forms: HashMap<String, Arc<form::PreparedForm>> = HashMap::new();
1630    for resource in &resources {
1631        let (mounted, prepared) = mount_resource(
1632            resource,
1633            &state.field_types,
1634            &state.column_types,
1635            &permission_codes,
1636            &persisters,
1637            &app_listeners,
1638        );
1639        protected = protected.merge(mounted);
1640        if let Some(prepared) = prepared {
1641            let key = resource
1642                .base_path
1643                .strip_prefix(admin_path.as_str())
1644                .unwrap_or(&resource.base_path);
1645            forms.insert(key.to_string(), prepared);
1646        }
1647    }
1648    let forms: form::Forms = Arc::new(forms);
1649    // The import pages under each resource that declared them. Uploads go to
1650    // the disk the application registered as `private`, else the default under
1651    // the storage directory.
1652    let private_disk: Arc<dyn laterite_media::StorageDriver> = state
1653        .plugin_defined
1654        .items::<laterite_media::DiskReg>()
1655        .into_iter()
1656        .find(|d| d.name == import::DISK)
1657        .map(|d| d.driver.clone())
1658        .unwrap_or_else(|| {
1659            Arc::new(laterite_media::LocalDisk::new(format!(
1660                "{}/{}",
1661                config.storage_dir.trim_end_matches('/'),
1662                import::DISK
1663            )))
1664        });
1665    for resource in &resources {
1666        let Some(link) = &resource.list.import else {
1667            continue;
1668        };
1669        let key = resource
1670            .base_path
1671            .strip_prefix(admin_path.as_str())
1672            .unwrap_or(&resource.base_path)
1673            .to_string();
1674        let prepared = forms.get(&key).unwrap_or_else(|| {
1675            panic!(
1676                "admin resource `{}` declares `import` but has no form to import through",
1677                resource.base_path
1678            )
1679        });
1680        let feature = import::ImportFeature {
1681            disk: private_disk.clone(),
1682        };
1683        let base = link.href.clone();
1684        let ctx = routes::RouteCtx::new(
1685            state.db.clone(),
1686            &base,
1687            &admin_path,
1688            &state.origin,
1689            state.plugin_defined.clone(),
1690            state.auth.events().clone(),
1691            forms.clone(),
1692        );
1693        let info = routes::ResourceInfo::new(
1694            key,
1695            resource.base_path.clone(),
1696            resource.nav_label.clone(),
1697            link.permission.clone(),
1698            form::FormHandle::new(state.db.clone(), prepared.clone()),
1699        );
1700        protected = protected.merge(guard_with_permission(
1701            Router::new()
1702                .nest_service(&base, routes::ResourceFeature::mount(&feature, &ctx, &info)),
1703            &link.permission,
1704        ));
1705    }
1706    // A module's own screens: routes it wrote, mounted inside the protected tree
1707    // so they inherit the session, the permission guard, CSRF and the error pages.
1708    // Nested as a service, so the screen's router carries no framework state.
1709    for reg in &app_screens {
1710        let base = format!("{admin_path}{}", reg.base_path);
1711        let ctx = routes::RouteCtx::new(
1712            state.db.clone(),
1713            &base,
1714            &admin_path,
1715            &state.origin,
1716            state.plugin_defined.clone(),
1717            state.auth.events().clone(),
1718            forms.clone(),
1719        );
1720        protected = protected.merge(guard_with_permission(
1721            Router::new().nest_service(&base, reg.screen.mount(&ctx)),
1722            &reg.permission,
1723        ));
1724    }
1725
1726    // The roles screen has a dedicated create/edit form (the permission editor),
1727    // gated by the same permission as its list.
1728    protected = protected.merge(guard_with_permission(
1729        Router::new()
1730            .route(
1731                &format!("{admin_path}/roles/new"),
1732                get(roles::new_form).post(roles::create),
1733            )
1734            .route(
1735                &format!("{admin_path}/roles/{{id}}/edit"),
1736                get(roles::edit_form).post(roles::update),
1737            ),
1738        "backend.manage_roles",
1739    ));
1740    // The backend users screen edits a user's per-permission overrides, gated by
1741    // the same permission as its list.
1742    protected = protected.merge(guard_with_permission(
1743        Router::new()
1744            .route(
1745                &format!("{admin_path}/users/new"),
1746                get(users::new_form).post(users::create),
1747            )
1748            .route(
1749                &format!("{admin_path}/users/{{id}}/edit"),
1750                get(users::edit_form).post(users::update),
1751            )
1752            .route(
1753                &format!("{admin_path}/users/{{id}}/active"),
1754                post(users::set_active),
1755            )
1756            .route(
1757                &format!("{admin_path}/users/{{id}}/password"),
1758                post(users::reset_password),
1759            )
1760            .route(
1761                &format!("{admin_path}/users/{{id}}/unlock"),
1762                post(users::unlock),
1763            ),
1764        "backend.manage_users",
1765    ));
1766    // The plugins screen lists the installed plugins and toggles each on or off
1767    // (an intent applied on the next boot), gated by its own permission.
1768    protected = protected.merge(guard_with_permission(
1769        Router::new()
1770            .route(&format!("{admin_path}/plugins"), get(plugins::index))
1771            .route(
1772                &format!("{admin_path}/plugins/toggle"),
1773                post(plugins::toggle),
1774            ),
1775        plugins::MANAGE_PERMISSION,
1776    ));
1777    protected = protected
1778        .route(&format!("{admin_path}/settings"), get(settings_index))
1779        .route(
1780            &format!("{admin_path}/preferences"),
1781            get(preferences_form).post(preferences_update),
1782        )
1783        .route(
1784            &format!("{admin_path}/preferences/password"),
1785            post(password_update),
1786        )
1787        .route(
1788            &format!("{admin_path}/preferences/menu"),
1789            post(menu_order_update),
1790        )
1791        .route(&format!("{admin_path}/palette"), get(palette::palette))
1792        .route(
1793            &format!("{admin_path}/preferences/sessions/revoke"),
1794            post(session_revoke),
1795        )
1796        .route(
1797            &format!("{admin_path}/preferences/sessions/revoke-others"),
1798            post(session_revoke_others),
1799        )
1800        // Picker endpoints, served with the QUERY method (a read; the guard in the
1801        // handler answers 405 for any other method).
1802        .route(
1803            &format!("{admin_path}/pickers/{{source}}/search"),
1804            any(picker::search),
1805        )
1806        .route(
1807            &format!("{admin_path}/pickers/{{source}}/resolve"),
1808            any(picker::resolve),
1809        )
1810        .route(&format!("{admin_path}/logout"), post(logout));
1811
1812    // A route per settings screen, at the path its module resolved to, rather
1813    // than one parameterised route keyed by storage code. The code is captured
1814    // here, so it never has to survive a trip through the URL.
1815    for item in settings.iter().filter(|i| i.link.is_none()) {
1816        let path = format!("{admin_path}{}", item.route());
1817        let code = item.code.clone();
1818        let edit_code = code.clone();
1819        protected = protected.route(
1820            &path,
1821            get(
1822                move |State(state): State<AdminState>,
1823                      Extension(shell): Extension<Shell>,
1824                      Extension(user): Extension<AuthenticatedUser>| {
1825                    let code = edit_code.clone();
1826                    async move { settings_edit(state, shell, user, code).await }
1827                },
1828            )
1829            .post(
1830                move |State(state): State<AdminState>,
1831                      Extension(shell): Extension<Shell>,
1832                      Extension(user): Extension<AuthenticatedUser>,
1833                      Extension(session): Extension<session::SessionHandle>,
1834                      Form(data): Form<HashMap<String, String>>| {
1835                    let code = code.clone();
1836                    async move { settings_update(state, shell, user, session, code, data).await }
1837                },
1838            ),
1839        );
1840    }
1841
1842    protected
1843        .route_layer(middleware::from_fn_with_state(state.clone(), require_auth))
1844        // Public routes (not covered by the guard above): the login and first-run
1845        // setup screens and the embedded stylesheet and fonts (needed before
1846        // authentication).
1847        .route(
1848            &format!("{admin_path}/login"),
1849            get(login_form).post(login_submit),
1850        )
1851        .route(
1852            &format!("{admin_path}/setup"),
1853            get(setup_form).post(setup_submit),
1854        )
1855        .route(&format!("{admin_path}/assets/{{*path}}"), get(serve_asset))
1856        // A module's own public endpoints, at the literal paths they declared and
1857        // outside the admin entirely: no session, no permission, no chrome. They
1858        // sit above the fallback, so an unmatched URL still renders the 404.
1859        .merge(mount_public(
1860            &app_public,
1861            &state.db,
1862            &admin_path,
1863            &state.origin,
1864            &state.plugin_defined,
1865            state.auth.events(),
1866            &forms,
1867        ))
1868        // Unmatched URLs render the styled 404; a handler panic renders the 500.
1869        .fallback(not_found_fallback)
1870        // The CSRF origin gate wraps every route (login and setup included); the
1871        // panic layer is outermost so it catches everything.
1872        .layer(middleware::from_fn_with_state(
1873            state.clone(),
1874            enforce_origin,
1875        ))
1876        // Outside the origin gate, so a rejected request is still logged with
1877        // the address it came from.
1878        .layer(middleware::from_fn_with_state(
1879            state.clone(),
1880            capture_client,
1881        ))
1882        // Admin responses are per-operator and carry a request token, so no
1883        // shared cache may hold one and no browser may leave one on disk for
1884        // the next person at the machine. `if_not_present` leaves the asset
1885        // routes alone: those set their own policy from their URL.
1886        .layer(
1887            tower_http::set_header::SetResponseHeaderLayer::if_not_present(
1888                header::CACHE_CONTROL,
1889                axum::http::HeaderValue::from_static(http_cache::PRIVATE_NO_STORE),
1890            ),
1891        )
1892        // An htmx fragment and the full page share a URL and differ only by the
1893        // request header, so any cache keying on URL alone would serve one for
1894        // the other.
1895        .layer(
1896            tower_http::set_header::SetResponseHeaderLayer::if_not_present(
1897                header::VARY,
1898                axum::http::HeaderValue::from_static("HX-Request"),
1899            ),
1900        )
1901        .layer(tower_http::catch_panic::CatchPanicLayer::custom(
1902            handle_panic,
1903        ))
1904        .with_state(state)
1905}
1906
1907/// Fallback for unmatched admin URLs: a styled 404.
1908/// The styled 404, counted in the request log first.
1909async fn not_found_fallback(
1910    State(state): State<AdminState>,
1911    method: axum::http::Method,
1912    uri: axum::http::Uri,
1913) -> AdminError {
1914    requestlog::record(&state.db, method.as_str(), uri.path(), 404).await;
1915    AdminError::NotFound
1916}
1917
1918/// The styled 404 for a nested public route, which carries no admin state.
1919async fn not_found_plain() -> AdminError {
1920    AdminError::NotFound
1921}
1922
1923/// Turns a handler panic into a logged, styled 500.
1924fn handle_panic(err: Box<dyn std::any::Any + Send + 'static>) -> Response {
1925    let cause = err
1926        .downcast_ref::<&str>()
1927        .map(|s| s.to_string())
1928        .or_else(|| err.downcast_ref::<String>().cloned())
1929        .unwrap_or_else(|| "unknown panic".to_string());
1930    tracing::error!(panic = cause, "admin handler panicked");
1931    error::masked_500()
1932}
1933
1934/// Normalises a configured admin path: a single leading slash, no trailing
1935/// slash, falling back to `/admin` when empty. `manage`, `/manage`, and
1936/// `/manage/` all become `/manage`. Shared by [`router`] and any caller building
1937/// the panel's URL (for example a startup banner), so the two never drift.
1938pub fn normalize_path(path: &str) -> String {
1939    let trimmed = path.trim().trim_matches('/');
1940    if trimmed.is_empty() {
1941        "/admin".to_string()
1942    } else {
1943        format!("/{trimmed}")
1944    }
1945}
1946
1947/// Resolves a resource's authored-relative paths (`base_path`, the list's
1948/// `edit_base`, the form's `base_path`) to full paths under the admin mount.
1949/// Every contributed public route, nested at its declared path.
1950fn mount_public(
1951    regs: &[routes::PublicRouteReg],
1952    db: &Db,
1953    admin_path: &str,
1954    origin: &str,
1955    plugin_defined: &Arc<laterite_core::Registry>,
1956    events: &laterite_core::Events,
1957    forms: &form::Forms,
1958) -> Router<AdminState> {
1959    let mut router = Router::new();
1960    for reg in regs {
1961        let ctx = routes::RouteCtx::new(
1962            db.clone(),
1963            &reg.path,
1964            admin_path,
1965            origin,
1966            plugin_defined.clone(),
1967            events.clone(),
1968            forms.clone(),
1969        );
1970        // A nested service does not inherit the outer fallback, so without this a
1971        // request *below* a public route (`/robots.txt/anything`) escapes into
1972        // axum's bodyless 404 instead of the deployment's styled error page.
1973        // Pinned by a test, because it is a behaviour rather than a guarantee.
1974        router = router.nest_service(&reg.path, reg.route.mount(&ctx).fallback(not_found_plain));
1975    }
1976    router
1977}
1978
1979/// Moves a resource to `base`, taking its list and form links with it. Used when
1980/// a module's screens resolve to a namespaced or overridden path.
1981pub(crate) fn rebase_resource(base: &str, resource: &mut Resource) {
1982    let old = resource.base_path.clone();
1983    resource.base_path = base.to_string();
1984    if let Some(edit_base) = &mut resource.list.edit_base {
1985        if edit_base == &old {
1986            *edit_base = base.to_string();
1987        }
1988    }
1989    if let Some(form) = &mut resource.form {
1990        if form.base_path == old {
1991            form.base_path = base.to_string();
1992        }
1993    }
1994}
1995
1996fn prefix_resource(admin_path: &str, resource: &mut Resource) {
1997    resource.base_path = format!("{admin_path}{}", resource.base_path);
1998    if let Some(edit_base) = &mut resource.list.edit_base {
1999        *edit_base = format!("{admin_path}{edit_base}");
2000    }
2001    if let Some(form) = &mut resource.form {
2002        form.base_path = format!("{admin_path}{}", form.base_path);
2003    }
2004}
2005
2006/// One embedded admin asset served by [`serve_asset`].
2007pub(crate) struct AdminAsset {
2008    pub mime: &'static str,
2009    /// Borrowed for assets compiled in, owned for the icon sprite, which is
2010    /// assembled at boot from the framework's set plus whatever modules
2011    /// contributed and so cannot come from a file.
2012    pub bytes: std::borrow::Cow<'static, [u8]>,
2013}
2014
2015/// Admin assets served under `{admin}/assets/`, keyed by path. An open registry:
2016/// field types and plugins contribute their own (wired when the first one does).
2017pub(crate) type AssetRegistry = HashMap<&'static str, AdminAsset>;
2018
2019/// Registry key to the path it is served at, each carrying a digest of its
2020/// bytes. Built once at boot, since the bytes are compiled in and cannot change
2021/// while the process runs.
2022pub(crate) type AssetUrls = HashMap<&'static str, String>;
2023
2024/// Names every registered asset by its content.
2025pub(crate) fn asset_urls(registry: &AssetRegistry) -> AssetUrls {
2026    registry
2027        .iter()
2028        .map(|(&key, asset)| {
2029            (
2030                key,
2031                http_cache::fingerprint(key, &http_cache::digest(&asset.bytes)),
2032            )
2033        })
2034        .collect()
2035}
2036
2037/// Resolves widget asset keys to per-page assets for the shell: an order-
2038/// preserving dedup, a single URL builder (`{base}/assets/{key}`), and
2039/// stylesheet-vs-script by the registry's mime. A key absent from the registry is
2040/// skipped and trips a debug assertion, since a declared asset must be registered.
2041/// The URL is stamped as `data-lat-asset` in the head so a later htmx fragment's
2042/// `lat.assets.ensure` of the same key is a no-op.
2043pub(crate) fn page_assets(
2044    keys: &[&str],
2045    base: &str,
2046    registry: &AssetRegistry,
2047    urls: &AssetUrls,
2048) -> Vec<PageAsset> {
2049    let mut seen = std::collections::HashSet::new();
2050    let mut out = Vec::new();
2051    for &key in keys {
2052        if !seen.insert(key) {
2053            continue;
2054        }
2055        match (registry.get(key), urls.get(key)) {
2056            (Some(asset), Some(path)) => out.push(PageAsset {
2057                url: format!("{base}/assets/{path}"),
2058                css: asset.mime.contains("css"),
2059            }),
2060            _ => debug_assert!(false, "asset key `{key}` is not registered"),
2061        }
2062    }
2063    out
2064}
2065
2066/// The framework's built-in assets: the stylesheet, brand marks, and webfonts.
2067///
2068/// None of them declares a cache policy. Every one is referenced through
2069/// [`asset_urls`], which names each by a digest of its bytes, and
2070/// [`serve_asset`] reads the policy off the URL: a request that named the
2071/// content may keep it forever, one that did not must revalidate. So an asset
2072/// changed by a framework upgrade reaches a browser that had cached the old
2073/// one, without anybody remembering to say so.
2074pub(crate) fn builtin_assets() -> AssetRegistry {
2075    let font = |bytes: &'static [u8]| AdminAsset {
2076        mime: "font/woff2",
2077        bytes: std::borrow::Cow::Borrowed(bytes),
2078    };
2079    HashMap::from([
2080        (
2081            "laterite.css",
2082            AdminAsset {
2083                mime: "text/css; charset=utf-8",
2084                bytes: std::borrow::Cow::Borrowed(include_bytes!("../assets/laterite.css")),
2085            },
2086        ),
2087        (
2088            "laterite.js",
2089            AdminAsset {
2090                mime: "text/javascript; charset=utf-8",
2091                bytes: std::borrow::Cow::Borrowed(include_bytes!("../assets/laterite.js")),
2092            },
2093        ),
2094        (
2095            "vendor/htmx.min.js",
2096            AdminAsset {
2097                mime: "text/javascript; charset=utf-8",
2098                bytes: std::borrow::Cow::Borrowed(include_bytes!("../assets/vendor/htmx.min.js")),
2099            },
2100        ),
2101        (
2102            "fields/ref-picker.js",
2103            AdminAsset {
2104                mime: "text/javascript; charset=utf-8",
2105                bytes: std::borrow::Cow::Borrowed(include_bytes!("../assets/fields/ref-picker.js")),
2106            },
2107        ),
2108        (
2109            "fields/ref-picker.css",
2110            AdminAsset {
2111                mime: "text/css; charset=utf-8",
2112                bytes: std::borrow::Cow::Borrowed(include_bytes!(
2113                    "../assets/fields/ref-picker.css"
2114                )),
2115            },
2116        ),
2117        (
2118            "mark.svg",
2119            AdminAsset {
2120                mime: "image/svg+xml",
2121                bytes: std::borrow::Cow::Borrowed(include_bytes!("../assets/mark.svg")),
2122            },
2123        ),
2124        (
2125            "mark.png",
2126            AdminAsset {
2127                mime: "image/png",
2128                bytes: std::borrow::Cow::Borrowed(include_bytes!("../assets/mark.png")),
2129            },
2130        ),
2131        (
2132            "fonts/space-grotesk-500.woff2",
2133            font(include_bytes!("../assets/fonts/space-grotesk-500.woff2")),
2134        ),
2135        (
2136            "fonts/space-grotesk-600.woff2",
2137            font(include_bytes!("../assets/fonts/space-grotesk-600.woff2")),
2138        ),
2139        (
2140            "fonts/space-grotesk-700.woff2",
2141            font(include_bytes!("../assets/fonts/space-grotesk-700.woff2")),
2142        ),
2143        (
2144            "fonts/ibm-plex-sans-400.woff2",
2145            font(include_bytes!("../assets/fonts/ibm-plex-sans-400.woff2")),
2146        ),
2147        (
2148            "fonts/ibm-plex-sans-600.woff2",
2149            font(include_bytes!("../assets/fonts/ibm-plex-sans-600.woff2")),
2150        ),
2151        (
2152            "fonts/ibm-plex-mono-400.woff2",
2153            font(include_bytes!("../assets/fonts/ibm-plex-mono-400.woff2")),
2154        ),
2155        (
2156            "fonts/ibm-plex-mono-600.woff2",
2157            font(include_bytes!("../assets/fonts/ibm-plex-mono-600.woff2")),
2158        ),
2159    ])
2160}
2161
2162/// Serves an embedded admin asset by path (public; no auth).
2163async fn serve_asset(
2164    State(state): State<AdminState>,
2165    headers: HeaderMap,
2166    Path(path): Path<String>,
2167) -> Response {
2168    // A URL that named the content is answerable forever, because different
2169    // bytes would have been a different URL. One that did not gets a validator
2170    // instead, so the next request is a cheap 304 rather than a fresh download.
2171    let (key, fingerprinted) = http_cache::strip_fingerprint(&path);
2172    let Some(asset) = state.assets.get(key.as_str()) else {
2173        return not_found();
2174    };
2175    let policy = if fingerprinted {
2176        http_cache::IMMUTABLE
2177    } else {
2178        http_cache::REVALIDATE
2179    };
2180    http_cache::conditional(&headers, asset.mime, policy, asset.bytes.to_vec())
2181}
2182
2183/// Builds a resource's list, create, and edit routes as generic handlers that
2184/// carry the resource's descriptors. When the resource sets a `permission`, every
2185/// route it mounts is wrapped in a guard that answers `403 Forbidden` for an
2186/// operator who lacks it; the caller merges the result into the protected router.
2187fn mount_resource(
2188    resource: &Resource,
2189    field_types: &field::FieldRegistry,
2190    column_types: &list::ColumnRegistry,
2191    permission_codes: &std::collections::HashSet<String>,
2192    persisters: &persist::PersisterRegistry,
2193    listeners: &[laterite_core::ModelListenerReg],
2194) -> (Router<AdminState>, Option<Arc<form::PreparedForm>>) {
2195    // A column naming a type nobody registered used to render an empty cell;
2196    // it aborts boot instead, like a form field with an unregistered type. So
2197    // does a column requiring a permission nobody registered.
2198    list::check(&resource.list, column_types, permission_codes)
2199        .unwrap_or_else(|e| panic!("admin resource `{}`: {e}", resource.base_path));
2200    // A write resource must be permission-gated. A create/edit form with no
2201    // permission would expose its mutations to every signed-in operator, so an
2202    // unguarded form is a wiring bug that aborts boot (a read-only list may omit a
2203    // permission). If a public write resource is ever wanted, it opts in explicitly.
2204    if resource.form.is_some() && resource.permission.is_none() {
2205        panic!(
2206            "admin resource `{}` has a create/edit form but no permission; a write \
2207             resource must declare a permission",
2208            resource.base_path
2209        );
2210    }
2211    let base = resource.base_path.clone();
2212    let list_path = base.clone();
2213    let mut list_cfg = resource.list.clone();
2214    // Editable cells write through the resource's form, prepared here for
2215    // them: a column that edits a field the form lacks aborts boot.
2216    if resource.list.columns.iter().any(|c| c.editable) {
2217        let Some(form_cfg) = resource.form.clone() else {
2218            panic!(
2219                "admin resource `{}` has an editable column but no form to edit through",
2220                resource.base_path
2221            );
2222        };
2223        for column in resource.list.columns.iter().filter(|c| c.editable) {
2224            if !form_cfg.fields.iter().any(|f| f.name == column.field) {
2225                panic!(
2226                    "admin resource `{}`: column `{}` is editable but the form has no such field",
2227                    resource.base_path, column.field
2228                );
2229            }
2230        }
2231        let prepared = form::PreparedForm::prepare(form_cfg, field_types, persisters, listeners)
2232            .unwrap_or_else(|e| panic!("admin resource `{}`: {e}", resource.base_path));
2233        list_cfg.editor = Some(list::Editor(Arc::new(prepared)));
2234    }
2235    let cell_cfg = list_cfg.clone();
2236    let mut router = Router::new().route(
2237        &base,
2238        get(
2239            move |State(state): State<AdminState>,
2240                  Extension(shell): Extension<Shell>,
2241                  Query(params): Query<list::ListParams>,
2242                  Query(raw): Query<std::collections::HashMap<String, String>>,
2243                  axum::extract::RawQuery(query_string): axum::extract::RawQuery,
2244                  Extension(user): Extension<AuthenticatedUser>,
2245                  Extension(session): Extension<session::SessionHandle>,
2246                  headers: axum::http::HeaderMap| {
2247                let cfg = list_cfg.clone();
2248                let path = list_path.clone();
2249                async move {
2250                    list::handle_remembering(
2251                        &state,
2252                        &cfg,
2253                        &path,
2254                        params,
2255                        &raw,
2256                        &user,
2257                        shell,
2258                        &headers,
2259                        query_string.as_deref(),
2260                        Some(&session),
2261                    )
2262                    .await
2263                }
2264            },
2265        ),
2266    );
2267
2268    if cell_cfg.editor.is_some() {
2269        let (cfg, list_path) = (cell_cfg, base.clone());
2270        router = router.route(
2271            &format!("{base}/{{id}}/cell"),
2272            post(
2273                move |State(state): State<AdminState>,
2274                      Extension(shell): Extension<Shell>,
2275                      Extension(user): Extension<AuthenticatedUser>,
2276                      Extension(session): Extension<session::SessionHandle>,
2277                      Path(id): Path<String>,
2278                      headers: axum::http::HeaderMap,
2279                      Form(data): Form<HashMap<String, String>>| {
2280                    let (cfg, path) = (cfg.clone(), list_path.clone());
2281                    async move {
2282                        list::cell_handler(
2283                            &state, &cfg, &path, &id, &user, &session, shell, &headers, data,
2284                        )
2285                        .await
2286                    }
2287                },
2288            ),
2289        );
2290    }
2291
2292    // Not registered at all when the resource has not opted in, so the capability
2293    // cannot be reached by guessing the URL.
2294    let (export_cfg, export_path) = (resource.list.clone(), resource.base_path.clone());
2295    if resource.list.exportable {
2296        router = router.route(
2297            &format!("{base}/export"),
2298            get(
2299                move |state: State<AdminState>,
2300                      Query(raw): Query<std::collections::HashMap<String, String>>,
2301                      Extension(user): Extension<AuthenticatedUser>,
2302                      Extension(shell): Extension<Shell>,
2303                      Extension(session): Extension<session::SessionHandle>| {
2304                    let cfg = export_cfg.clone();
2305                    let path = export_path.clone();
2306                    async move {
2307                        export::handle(state, &cfg, &path, &raw, &user, &shell, &session).await
2308                    }
2309                },
2310            ),
2311        );
2312    }
2313
2314    let (columns_cfg, columns_path) = (resource.list.clone(), resource.base_path.clone());
2315    router = router.route(
2316        &format!("{base}/columns"),
2317        post(
2318            move |State(state): State<AdminState>,
2319                  Extension(user): Extension<AuthenticatedUser>,
2320                  Extension(session): Extension<session::SessionHandle>,
2321                  headers: axum::http::HeaderMap,
2322                  Form(pairs): Form<Vec<(String, String)>>| {
2323                let cfg = columns_cfg.clone();
2324                let path = columns_path.clone();
2325                async move {
2326                    list::set_columns(&state, &cfg, &path, &user, &session, &headers, &pairs).await
2327                }
2328            },
2329        ),
2330    );
2331
2332    if resource.list.deletable {
2333        // The write path for a delete: the form's persister when the resource has
2334        // a generic form, otherwise one over the list's own table, so a bespoke
2335        // editor (roles) still deletes through the pipeline rather than beside it.
2336        let persister: Arc<dyn persist::Persister> =
2337            match resource.form.as_ref().and_then(|f| f.persist.as_ref()) {
2338                Some(key) => persisters.get(key).cloned().unwrap_or_else(|| {
2339                    panic!(
2340                        "admin resource `{}`: unregistered persister `{key}`",
2341                        resource.base_path
2342                    )
2343                }),
2344                None => Arc::new(persist::DefaultPersister::from_list(&resource.list)),
2345            };
2346        let ctx = Arc::new(bulk::BulkContext {
2347            base_path: resource.base_path.clone(),
2348            entity: resource.list.entity.clone(),
2349            persister,
2350            listeners: listeners
2351                .iter()
2352                .filter(|reg| reg.matches(&resource.list.entity))
2353                .map(|reg| reg.listener.clone())
2354                .collect(),
2355        });
2356        router =
2357            router.route(
2358                &format!("{base}/delete"),
2359                post(
2360                    move |state: State<AdminState>,
2361                          user: Extension<AuthenticatedUser>,
2362                          session: Extension<session::SessionHandle>,
2363                          headers: axum::http::HeaderMap,
2364                          form: Form<Vec<(String, String)>>| {
2365                        let ctx = ctx.clone();
2366                        async move {
2367                            bulk::delete_handler(state, user, session, ctx, headers, form).await
2368                        }
2369                    },
2370                ),
2371            );
2372    }
2373
2374    // A tree with a picker source offers "Move to": the one-field form over
2375    // the parent column, writing through the resource's own persister.
2376    if let Some(source) = resource.list.tree.as_ref().and_then(|t| t.source.clone()) {
2377        let tree = resource.list.tree.clone().unwrap_or_default();
2378        let mut move_cfg = form::FormConfig::new(
2379            resource.list.entity.clone(),
2380            laterite_core::t!("Move to"),
2381            base.clone(),
2382            resource.list.id_field.clone(),
2383            vec![form::FormField::reference(
2384                &tree.parent_key,
2385                laterite_core::t!("New parent"),
2386                &source,
2387            )
2388            .help(laterite_core::t!("Leave empty for the top level."))],
2389        );
2390        if let Some(persist) = resource.form.as_ref().and_then(|f| f.persist.clone()) {
2391            move_cfg = move_cfg.persist(persist);
2392        }
2393        move_cfg.done_path = Some(base.clone());
2394        let move_form = Arc::new(
2395            form::PreparedForm::prepare(move_cfg, field_types, persisters, listeners)
2396                .unwrap_or_else(|e| panic!("admin resource `{}`: {e}", resource.base_path)),
2397        );
2398        let (cfg, list_path) = (resource.list.clone(), base.clone());
2399        let (form_get, form_post) = (move_form.clone(), move_form);
2400        let (cfg_post, path_post) = (cfg.clone(), list_path.clone());
2401        router = router.route(
2402            &format!("{base}/{{id}}/move"),
2403            get(
2404                move |State(state): State<AdminState>,
2405                      Extension(shell): Extension<Shell>,
2406                      Path(id): Path<String>| {
2407                    let (cfg, path, pf) = (cfg.clone(), list_path.clone(), form_get.clone());
2408                    async move { list::move_form(&state, &cfg, &pf, &path, &id, shell).await }
2409                },
2410            )
2411            .post(
2412                move |State(state): State<AdminState>,
2413                      Extension(shell): Extension<Shell>,
2414                      Extension(user): Extension<AuthenticatedUser>,
2415                      Extension(session): Extension<session::SessionHandle>,
2416                      Path(id): Path<String>,
2417                      headers: axum::http::HeaderMap,
2418                      Form(data): Form<HashMap<String, String>>| {
2419                    let (cfg, path, pf) = (cfg_post.clone(), path_post.clone(), form_post.clone());
2420                    async move {
2421                        list::move_record(
2422                            &state, &cfg, &pf, &path, &id, &user, &session, shell, &headers, data,
2423                        )
2424                        .await
2425                    }
2426                },
2427            ),
2428        );
2429    }
2430
2431    if resource.list.reorder.is_some() {
2432        let (cfg, list_path) = (resource.list.clone(), base.clone());
2433        router = router.route(
2434            &format!("{base}/reorder"),
2435            post(
2436                move |State(state): State<AdminState>,
2437                      Extension(shell): Extension<Shell>,
2438                      Extension(user): Extension<AuthenticatedUser>,
2439                      Extension(session): Extension<session::SessionHandle>,
2440                      headers: axum::http::HeaderMap,
2441                      Form(pairs): Form<Vec<(String, String)>>| {
2442                    let cfg = cfg.clone();
2443                    let path = list_path.clone();
2444                    async move {
2445                        list::reorder_handler(
2446                            &state, &cfg, &path, "lat-list", None, &user, &session, shell,
2447                            &headers, &pairs,
2448                        )
2449                        .await
2450                    }
2451                },
2452            ),
2453        );
2454    }
2455
2456    // Relations, each resolved once here: its child form prepared, its routes
2457    // under `{base}/{id}/{name}`, its section on the parent's edit page.
2458    if !resource.relations.is_empty() && resource.form.is_none() {
2459        panic!(
2460            "admin resource `{}` declares relations but has no form to show them on",
2461            resource.base_path
2462        );
2463    }
2464    let mut relations: Vec<Arc<relation::PreparedRelation>> = Vec::new();
2465    for rel in &resource.relations {
2466        let prepared = relation::PreparedRelation::prepare(
2467            resource,
2468            rel.clone(),
2469            field_types,
2470            column_types,
2471            permission_codes,
2472            persisters,
2473            listeners,
2474        )
2475        .unwrap_or_else(|e| panic!("admin resource `{}`: {e}", resource.base_path));
2476        relations.push(Arc::new(prepared));
2477    }
2478    let relations = Arc::new(relations);
2479
2480    let mut prepared_form = None;
2481    if let Some(form_cfg) = resource.form.clone() {
2482        // Resolve the form's field options once, here at router build. A malformed
2483        // option or unregistered type aborts boot naming the resource.
2484        let mut prepared =
2485            form::PreparedForm::prepare(form_cfg, field_types, persisters, listeners)
2486                .unwrap_or_else(|e| panic!("admin resource `{}`: {e}", resource.base_path));
2487        // Sections live on the edit page, so a form with them offers to stay there.
2488        prepared.stay = !relations.is_empty();
2489        let prepared = Arc::new(prepared);
2490        prepared_form = Some(prepared.clone());
2491        let (new_pf, create_pf) = (prepared.clone(), prepared.clone());
2492        let relations_for_new = relations.clone();
2493        router = router.route(
2494            &format!("{base}/new"),
2495            get(
2496                move |State(state): State<AdminState>, Extension(shell): Extension<Shell>| {
2497                    let pf = new_pf.clone();
2498                    let relations = relations_for_new.clone();
2499                    async move {
2500                        let pending = relations
2501                            .iter()
2502                            .map(|r| shell.tt(&r.config.title))
2503                            .collect();
2504                        form::new_form(&state, &pf, shell, pending)
2505                    }
2506                },
2507            )
2508            .post(
2509                move |State(state): State<AdminState>,
2510                      Extension(shell): Extension<Shell>,
2511                      Extension(user): Extension<AuthenticatedUser>,
2512                      Extension(session): Extension<session::SessionHandle>,
2513                      headers: axum::http::HeaderMap,
2514                      Form(data): Form<HashMap<String, String>>| {
2515                    let pf = create_pf.clone();
2516                    async move {
2517                        form::create(&state, &pf, data, shell, &user, &session, &headers).await
2518                    }
2519                },
2520            ),
2521        );
2522
2523        let (edit_pf, update_pf) = (prepared.clone(), prepared.clone());
2524        let relations_for_edit = relations.clone();
2525        router = router.route(
2526            &format!("{base}/{{id}}/edit"),
2527            get(
2528                move |State(state): State<AdminState>,
2529                      Extension(shell): Extension<Shell>,
2530                      Extension(user): Extension<AuthenticatedUser>,
2531                      Path(id): Path<String>| {
2532                    let pf = edit_pf.clone();
2533                    let relations = relations_for_edit.clone();
2534                    async move {
2535                        let mut sections = Vec::new();
2536                        for rel in relations.iter() {
2537                            if let Some(section) = rel.section(&state, &id, &user, &shell).await {
2538                                sections.push(section);
2539                            }
2540                        }
2541                        form::edit_form(&state, &pf, id, shell, sections).await
2542                    }
2543                },
2544            )
2545            .post(
2546                move |State(state): State<AdminState>,
2547                      Extension(shell): Extension<Shell>,
2548                      Extension(user): Extension<AuthenticatedUser>,
2549                      Extension(session): Extension<session::SessionHandle>,
2550                      Path(id): Path<String>,
2551                      headers: axum::http::HeaderMap,
2552                      Form(data): Form<HashMap<String, String>>| {
2553                    let pf = update_pf.clone();
2554                    async move {
2555                        form::update(&state, &pf, id, data, shell, &user, &session, &headers).await
2556                    }
2557                },
2558            ),
2559        );
2560    }
2561
2562    for rel in relations.iter() {
2563        let name = rel.config.name.clone();
2564        let mut routes: Router<AdminState> = Router::new();
2565        let r = rel.clone();
2566        routes =
2567            routes.route(
2568                &format!("{base}/{{id}}/{name}"),
2569                get(
2570                    move |state: State<AdminState>,
2571                          shell: Extension<Shell>,
2572                          user: Extension<AuthenticatedUser>,
2573                          id: Path<String>,
2574                          params: Query<list::ListParams>,
2575                          raw: Query<HashMap<String, String>>,
2576                          headers: axum::http::HeaderMap| {
2577                        let r = r.clone();
2578                        async move {
2579                            relation::index(state, shell, user, id, params, raw, headers, r).await
2580                        }
2581                    },
2582                ),
2583            );
2584        let (r_new, r_create) = (rel.clone(), rel.clone());
2585        routes = routes.route(
2586            &format!("{base}/{{id}}/{name}/new"),
2587            get(
2588                move |state: State<AdminState>, shell: Extension<Shell>, id: Path<String>| {
2589                    let r = r_new.clone();
2590                    async move { relation::new_form(state, shell, id, r).await }
2591                },
2592            )
2593            .post(
2594                move |state: State<AdminState>,
2595                      shell: Extension<Shell>,
2596                      user: Extension<AuthenticatedUser>,
2597                      session: Extension<session::SessionHandle>,
2598                      id: Path<String>,
2599                      headers: axum::http::HeaderMap,
2600                      data: Form<HashMap<String, String>>| {
2601                    let r = r_create.clone();
2602                    async move {
2603                        relation::create(state, shell, user, session, id, headers, data, r).await
2604                    }
2605                },
2606            ),
2607        );
2608        let (r_edit, r_update) = (rel.clone(), rel.clone());
2609        routes = routes.route(
2610            &format!("{base}/{{id}}/{name}/{{child}}/edit"),
2611            get(
2612                move |state: State<AdminState>,
2613                      shell: Extension<Shell>,
2614                      ids: Path<(String, String)>| {
2615                    let r = r_edit.clone();
2616                    async move { relation::edit_form(state, shell, ids, r).await }
2617                },
2618            )
2619            .post(
2620                move |state: State<AdminState>,
2621                      shell: Extension<Shell>,
2622                      user: Extension<AuthenticatedUser>,
2623                      session: Extension<session::SessionHandle>,
2624                      ids: Path<(String, String)>,
2625                      headers: axum::http::HeaderMap,
2626                      data: Form<HashMap<String, String>>| {
2627                    let r = r_update.clone();
2628                    async move {
2629                        relation::update(state, shell, user, session, ids, headers, data, r).await
2630                    }
2631                },
2632            ),
2633        );
2634        let r_delete = rel.clone();
2635        routes = routes.route(
2636            &format!("{base}/{{id}}/{name}/delete"),
2637            post(
2638                move |state: State<AdminState>,
2639                      shell: Extension<Shell>,
2640                      user: Extension<AuthenticatedUser>,
2641                      session: Extension<session::SessionHandle>,
2642                      id: Path<String>,
2643                      headers: axum::http::HeaderMap,
2644                      pairs: Form<Vec<(String, String)>>| {
2645                    let r = r_delete.clone();
2646                    async move {
2647                        relation::delete(state, shell, user, session, id, headers, pairs, r).await
2648                    }
2649                },
2650            ),
2651        );
2652        if rel.reorderable() {
2653            let r_reorder = rel.clone();
2654            routes = routes.route(
2655                &format!("{base}/{{id}}/{name}/reorder"),
2656                post(
2657                    move |state: State<AdminState>,
2658                          shell: Extension<Shell>,
2659                          user: Extension<AuthenticatedUser>,
2660                          session: Extension<session::SessionHandle>,
2661                          id: Path<String>,
2662                          headers: axum::http::HeaderMap,
2663                          pairs: Form<Vec<(String, String)>>| {
2664                        let r = r_reorder.clone();
2665                        async move {
2666                            relation::reorder(state, shell, user, session, id, headers, pairs, r)
2667                                .await
2668                        }
2669                    },
2670                ),
2671            );
2672        }
2673        if let Some(permission) = &rel.config.permission {
2674            routes = guard_with_permission(routes, permission);
2675        }
2676        router = router.merge(routes);
2677    }
2678
2679    // Gate every route the resource mounts on its permission.
2680    if let Some(permission) = &resource.permission {
2681        router = guard_with_permission(router, permission);
2682    }
2683    (router, prepared_form)
2684}
2685
2686/// Wraps every route currently in `router` in a permission guard: the auth guard
2687/// runs first and injects the identity, so this reads it from the request
2688/// extensions and answers `403 Forbidden` for an operator who lacks `permission`.
2689/// Shared by resource mounting and the roles permission editor.
2690fn guard_with_permission(router: Router<AdminState>, permission: &str) -> Router<AdminState> {
2691    let needed: Arc<str> = Arc::from(permission);
2692    router.route_layer(middleware::from_fn(
2693        move |Extension(user): Extension<AuthenticatedUser>, req: Request, next: Next| {
2694            let needed = needed.clone();
2695            async move {
2696                if user.allows(&needed) {
2697                    next.run(req).await
2698                } else {
2699                    forbidden()
2700                }
2701            }
2702        },
2703    ))
2704}
2705
2706/// The gate for authenticated admin routes. Resolves the session (identity plus
2707/// its opaque blob), verifies CSRF on state-changing requests, injects the
2708/// identity, shell, and a [`session::SessionHandle`] for handlers, and persists
2709/// the session blob afterwards when a handler changed it. Unauthenticated
2710/// requests redirect to the login screen.
2711async fn require_auth(
2712    State(state): State<AdminState>,
2713    jar: CookieJar,
2714    request: Request,
2715    next: Next,
2716) -> Response {
2717    let login = format!("{}/login", state.admin_path);
2718    let client_ctx = request
2719        .extensions()
2720        .get::<RequestContext>()
2721        .cloned()
2722        .unwrap_or_default();
2723    // A live session is the ordinary path. A missing or expired one falls back
2724    // to the stay-signed-in credential, which mints a fresh session and rotates
2725    // itself, so the cookie just presented is never accepted a second time.
2726    // A presented session that fails is asked why, so the login screen can say.
2727    let mut ended: Option<laterite_auth::SessionEnd> = None;
2728    let live = match jar.get(SESSION_COOKIE) {
2729        Some(cookie) => {
2730            let token = cookie.value().to_string();
2731            match state.auth.resolve_session(&token).await {
2732                Ok(resolved) => Some((token, resolved)),
2733                Err(_) => {
2734                    ended = state.auth.session_end(&token).await.ok().flatten();
2735                    None
2736                }
2737            }
2738        }
2739        None => None,
2740    };
2741    let htmx = request.headers().contains_key("hx-request");
2742    let (token, resolved, recalled) = match live {
2743        Some((token, resolved)) => (token, resolved, None),
2744        // Ended on purpose: the stay-signed-in credential was dropped with it,
2745        // and recalling past a deliberate sign-out would undo it anyway.
2746        None if matches!(ended, Some(laterite_auth::SessionEnd::Revoked(_))) => {
2747            return signed_out(&state, jar, &login, ended, htmx);
2748        }
2749        None => match recall(&state, &jar, &client_ctx).await {
2750            Some((token, resolved, credential)) => (token, resolved, Some(credential)),
2751            None => {
2752                // A device returning on its stay-signed-in cookie alone has no
2753                // session to say why; the credential itself may, and an ending
2754                // on purpose outranks a session that merely ran out.
2755                if let Some(cookie) = jar.get(REMEMBER_COOKIE) {
2756                    if let Ok(Some(reason)) = state.auth.remember_end(cookie.value()).await {
2757                        ended = Some(laterite_auth::SessionEnd::Revoked(reason));
2758                    }
2759                }
2760                return signed_out(&state, jar, &login, ended, htmx);
2761            }
2762        },
2763    };
2764    let handle = session::SessionHandle::from_blob(resolved.data.as_deref());
2765
2766    // CSRF token check (the origin gate already ran on the whole router). A
2767    // state-changing method must carry the session token in a header or the
2768    // `_csrf` field; buffering the body serves plain forms and HTMX alike and
2769    // fails closed when a form omitted the field.
2770    let mut request = request;
2771    let safe = session::is_safe_method(request.method());
2772    // Set when the token has to be checked by the handler's extractor instead.
2773    let mut deferred: Option<session::CsrfPending> = None;
2774    if !safe {
2775        let (parts, body) = request.into_parts();
2776        // A file upload is never buffered: the form limit would truncate it to
2777        // nothing (and the token check would then fail for the wrong reason),
2778        // and holding a whole file in memory to read one field defeats streaming
2779        // it. Such a request carries its token in the header, or in the form
2780        // action's query string when there is no scripting to set one. The body
2781        // passes through untouched.
2782        let (body, submitted) = if session::is_multipart(&parts.headers) {
2783            let token = session::header_token(&parts.headers)
2784                .or_else(|| session::query_token(parts.uri.query()));
2785            // No token beside the body means it is in the body, where the
2786            // reference system reads it from and where a plain form can put it.
2787            // The guard cannot look there without consuming the upload, so the
2788            // check is deferred to the extractor and enforced below.
2789            if token.is_none() {
2790                deferred = Some(session::CsrfPending::default());
2791            }
2792            (body, token)
2793        } else {
2794            let bytes = axum::body::to_bytes(body, MAX_FORM_BYTES)
2795                .await
2796                .unwrap_or_default();
2797            let token = session::submitted_token(&parts.headers, &bytes);
2798            (Body::from(bytes), token)
2799        };
2800        if deferred.is_none() && !session::token_matches(&handle.csrf_token(), submitted.as_deref())
2801        {
2802            tracing::warn!(
2803                user_id = resolved.identity.user.id,
2804                "admin CSRF check failed"
2805            );
2806            return error::csrf_rejected();
2807        }
2808        request = Request::from_parts(parts, body);
2809    }
2810
2811    let user = resolved.identity;
2812    // Kept past the move into the request, for the deferred-check log below.
2813    let acting_user_id = user.user.id;
2814    let path = request.uri().path().to_string();
2815    // A temporary password opens nothing but the Preferences form that replaces
2816    // it, and the way out.
2817    let preferences = format!("{}/preferences", state.admin_path);
2818    if !path.starts_with(&preferences)
2819        && path != format!("{}/logout", state.admin_path)
2820        && state
2821            .auth
2822            .must_change_password(user.user.id)
2823            .await
2824            .unwrap_or(false)
2825    {
2826        let to = format!("{preferences}#password");
2827        let response = if htmx {
2828            (
2829                [("HX-Redirect", to.as_str())],
2830                axum::http::StatusCode::NO_CONTENT,
2831            )
2832                .into_response()
2833        } else {
2834            Redirect::to(&to).into_response()
2835        };
2836        return with_recall_cookies(response, recalled, jar, token, &state);
2837    }
2838    // Deliver and clear any queued flash on a full-page render; a mutating
2839    // request leaves it for the redirect target's GET.
2840    let flash = if safe {
2841        handle.take_flash()
2842    } else {
2843        Vec::new()
2844    };
2845    // Resolve the locale chain for this request (operator preference, then the
2846    // browser's Accept-Language, then the deployment default) over the shared
2847    // catalogs, before the nav context, which localizes the settings sidebar.
2848    let accept_language = request
2849        .headers()
2850        .get("accept-language")
2851        .and_then(|v| v.to_str().ok());
2852    let serveable = state.catalogs.locales();
2853    let chain = resolve_locale_chain(
2854        user.user.locale.as_deref(),
2855        accept_language,
2856        &state.default_locale,
2857        &serveable,
2858    );
2859    let i18n = Translator::with_chain(chain, state.catalogs.clone());
2860    // A clone kept past `next` (the shell's copy moves into the request) to localize
2861    // an error response the handler renders English (the `ErrorMeta` seam).
2862    let translator = i18n.clone();
2863    // The operator's own order for the top bar, when they dragged one.
2864    let own_order =
2865        laterite_auth::store::user_preference(&state.db, user.user.id, nav::ORDER_PREFERENCE)
2866            .await
2867            .unwrap_or_default();
2868    let (visible_nav, sidebar, active_nav) = resolve_nav_context(
2869        &state.nav,
2870        &state.settings,
2871        &state.admin_path,
2872        &user.permissions,
2873        own_order.as_deref(),
2874        &path,
2875        &i18n,
2876        icons::Icons::new(&state.icons, &state.sprite_url),
2877    );
2878    let brand = state.brand().await;
2879    let shell = Shell::new(
2880        &state.admin_path,
2881        brand,
2882        &visible_nav,
2883        &user,
2884        state.timezone,
2885        sidebar,
2886        active_nav.as_deref(),
2887        handle.csrf_token(),
2888        flash,
2889        i18n,
2890        state.asset_urls.clone(),
2891        state.origin.to_string(),
2892        state.icons.clone(),
2893        state.sprite_url.clone(),
2894    );
2895    request.extensions_mut().insert(user);
2896    request.extensions_mut().insert(shell);
2897    request.extensions_mut().insert(handle.clone());
2898    // Present only when the token check was deferred to an upload extractor.
2899    if let Some(pending) = &deferred {
2900        request.extensions_mut().insert(pending.clone());
2901    }
2902    let mut response = next.run(request).await;
2903
2904    // A deferred check that never happened means the handler took the upload
2905    // without the verifying extractor. Refuse the response rather than let the
2906    // route quietly run unguarded: the origin gate held, but that is the outer
2907    // layer, not the whole of it.
2908    if let Some(pending) = &deferred {
2909        if !pending.was_satisfied() {
2910            tracing::error!(
2911                user_id = acting_user_id,
2912                "a multipart route returned without verifying its request token"
2913            );
2914            return error::csrf_rejected();
2915        }
2916    }
2917
2918    // The `ErrorMeta` seam: an `AdminError` renders its page in English from
2919    // `IntoResponse` (no request context there); re-render it localized now that a
2920    // translator is in hand. Status and kind are preserved.
2921    if let Some(meta) = response.extensions().get::<error::ErrorMeta>().copied() {
2922        response = error::localized_error(meta.kind, &translator);
2923    }
2924
2925    // Persist the blob only when a handler changed it (flash set or consumed,
2926    // token rotated, or a token freshly minted this request).
2927    if let Some(blob) = handle.dirty_blob() {
2928        if let Err(e) = state.auth.set_session_data(&token, &blob).await {
2929            tracing::error!(error = %e, "persisting admin session failed");
2930        }
2931    }
2932    with_recall_cookies(response, recalled, jar, token, &state)
2933}
2934
2935/// A recall replaced both halves, the session it minted and the credential that
2936/// replaced the one just spent, so every response on such a request carries the
2937/// new cookies, whichever branch produced it.
2938fn with_recall_cookies(
2939    response: Response,
2940    recalled: Option<laterite_auth::RememberCredential>,
2941    jar: CookieJar,
2942    token: String,
2943    state: &AdminState,
2944) -> Response {
2945    match recalled {
2946        Some(credential) => {
2947            let jar = jar
2948                .add(session_cookie(
2949                    token,
2950                    &state.admin_path,
2951                    state.secure_cookie,
2952                ))
2953                .add(remember_cookie(
2954                    credential,
2955                    &state.admin_path,
2956                    state.secure_cookie,
2957                ));
2958            (jar, response).into_response()
2959        }
2960        None => response,
2961    }
2962}
2963
2964/// Trades a presented stay-signed-in cookie for a live session. Returns the new
2965/// session token, the resolved identity, and the credential that replaces the
2966/// one just spent.
2967async fn recall(
2968    state: &AdminState,
2969    jar: &CookieJar,
2970    ctx: &RequestContext,
2971) -> Option<(
2972    String,
2973    laterite_auth::ResolvedSession,
2974    laterite_auth::RememberCredential,
2975)> {
2976    let presented = jar.get(REMEMBER_COOKIE)?.value().to_string();
2977    let recalled = state.auth.consume_remember(&presented, ctx).await.ok()?;
2978    let token = recalled.session.token.clone();
2979    let resolved = state.auth.resolve_session(&token).await.ok()?;
2980    Some((token, resolved, recalled.remember))
2981}
2982
2983/// Ceiling on a buffered admin form body for the CSRF check. Admin forms are
2984/// small; a larger body is rejected rather than buffered.
2985const MAX_FORM_BYTES: usize = 1024 * 1024;
2986
2987/// The primary CSRF gate, layered on the whole admin router: a state-changing
2988/// request must come from our own origin (see [`session::origin_ok`]). This
2989/// covers the login and setup screens, which are deliberately token-less (no
2990/// session exists yet), so the origin check is their sole CSRF defense.
2991/// Records where a request came from, once, for anything downstream that logs.
2992/// Doing it in one layer keeps the trusted-proxy rule in a single place rather
2993/// than at each call site that happens to want an address.
2994async fn capture_client(
2995    State(state): State<AdminState>,
2996    mut request: Request,
2997    next: Next,
2998) -> Response {
2999    let peer = request
3000        .extensions()
3001        .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
3002        .map(|info| info.0);
3003    let headers = request.headers();
3004    let ctx = RequestContext {
3005        ip_address: clientip::client_ip(peer, headers, &state.trusted_proxies),
3006        user_agent: clientip::user_agent(headers),
3007    };
3008    request.extensions_mut().insert(ctx);
3009    next.run(request).await
3010}
3011
3012async fn enforce_origin(State(state): State<AdminState>, request: Request, next: Next) -> Response {
3013    if !session::is_safe_method(request.method())
3014        && !session::origin_ok(request.headers(), &state.origin)
3015    {
3016        tracing::warn!(
3017            path = request.uri().path(),
3018            "admin CSRF origin check failed"
3019        );
3020        return error::csrf_rejected();
3021    }
3022    next.run(request).await
3023}
3024
3025#[derive(Deserialize)]
3026struct LoginQuery {
3027    ended: Option<String>,
3028}
3029
3030async fn login_form(
3031    State(state): State<AdminState>,
3032    headers: HeaderMap,
3033    Query(query): Query<LoginQuery>,
3034) -> Response {
3035    // A fresh install with no operators goes to first-run setup instead.
3036    match state.auth.has_any_operator().await {
3037        Ok(false) => Redirect::to(&format!("{}/setup", state.admin_path)).into_response(),
3038        Ok(true) => {
3039            let i18n = pre_auth_translator(&state, &headers);
3040            let notice = query
3041                .ended
3042                .as_deref()
3043                .and_then(end_notice)
3044                .map(|text| i18n.t(&text));
3045            render(LoginTemplate {
3046                base: state.admin_path.to_string(),
3047                asset_urls: state.asset_urls.clone(),
3048                brand: state.brand().await,
3049                error: None,
3050                notice,
3051                i18n,
3052            })
3053        }
3054        Err(_) => render_error(),
3055    }
3056}
3057
3058#[derive(Deserialize)]
3059struct LoginForm {
3060    username: String,
3061    password: String,
3062    /// The "Stay signed in" box. Present only when ticked, as a checkbox is.
3063    #[serde(default)]
3064    remember: Option<String>,
3065}
3066
3067async fn login_submit(
3068    State(state): State<AdminState>,
3069    jar: CookieJar,
3070    headers: HeaderMap,
3071    Extension(ctx): Extension<RequestContext>,
3072    Form(form): Form<LoginForm>,
3073) -> Response {
3074    match state
3075        .auth
3076        .authenticate(&form.username, &form.password, &ctx)
3077        .await
3078    {
3079        Ok(session) => {
3080            let wants_remember = form.remember.is_some();
3081            let user_id = session.user_id;
3082            let mut jar = jar.add(session_cookie(
3083                session.token,
3084                &state.admin_path,
3085                state.secure_cookie,
3086            ));
3087            if wants_remember {
3088                match state.auth.issue_remember(user_id).await {
3089                    Ok(credential) => {
3090                        jar = jar.add(remember_cookie(
3091                            credential,
3092                            &state.admin_path,
3093                            state.secure_cookie,
3094                        ));
3095                    }
3096                    // The session still stands; the box just did not take.
3097                    Err(e) => {
3098                        tracing::error!(error = %e, "issuing a stay-signed-in credential failed")
3099                    }
3100                }
3101            }
3102            (jar, Redirect::to(&state.admin_path)).into_response()
3103        }
3104        Err(_) => {
3105            let i18n = pre_auth_translator(&state, &headers);
3106            render(LoginTemplate {
3107                base: state.admin_path.to_string(),
3108                asset_urls: state.asset_urls.clone(),
3109                brand: state.brand().await,
3110                error: Some(i18n.t(&t!("Invalid username or password."))),
3111                notice: None,
3112                i18n,
3113            })
3114        }
3115    }
3116}
3117
3118/// Builds the session cookie, scoped to the admin mount and flagged `Secure`
3119/// behind HTTPS. Shared by login and first-run setup.
3120///
3121/// `remember` is what the login form's "Stay signed in" box asks for: the cookie
3122/// is given the session's own lifetime, so closing the browser does not end it.
3123/// Without it the cookie lasts the browser session, which is the right default
3124/// for a shared machine. Either way the cookie never outlives the session row it
3125/// names, because both take their length from the same place.
3126fn session_cookie(token: String, admin_path: &str, secure: bool) -> Cookie<'static> {
3127    Cookie::build((SESSION_COOKIE, token))
3128        .path(admin_path.to_string())
3129        .http_only(true)
3130        .secure(secure)
3131        .same_site(SameSite::Lax)
3132        .build()
3133}
3134
3135/// The "stay signed in" cookie. Outlives the session deliberately: when the
3136/// session ends, this is what mints the next one.
3137fn remember_cookie(
3138    credential: laterite_auth::RememberCredential,
3139    admin_path: &str,
3140    secure: bool,
3141) -> Cookie<'static> {
3142    let seconds = (credential.expires_at - chrono::Utc::now())
3143        .num_seconds()
3144        .max(0);
3145    Cookie::build((REMEMBER_COOKIE, credential.cookie))
3146        .path(admin_path.to_string())
3147        .http_only(true)
3148        .secure(secure)
3149        .same_site(SameSite::Lax)
3150        .max_age(cookie::time::Duration::seconds(seconds))
3151        .build()
3152}
3153
3154/// Sends a signed-out request to the login screen, carrying why when known.
3155///
3156/// Both cookies are cleared: a credential that failed once fails every time,
3157/// and retrying it on each request is noise. An htmx request gets `HX-Redirect`
3158/// with no body, so the browser navigates to the login page rather than
3159/// swapping it into whatever region asked.
3160fn signed_out(
3161    state: &AdminState,
3162    jar: CookieJar,
3163    login: &str,
3164    ended: Option<laterite_auth::SessionEnd>,
3165    htmx: bool,
3166) -> Response {
3167    let to = match ended.map(laterite_auth::SessionEnd::code) {
3168        Some(code) => format!("{login}?ended={code}"),
3169        None => login.to_string(),
3170    };
3171    let jar = jar
3172        .remove(
3173            Cookie::build((SESSION_COOKIE, ""))
3174                .path(state.admin_path.to_string())
3175                .build(),
3176        )
3177        .remove(remember_removal(&state.admin_path));
3178    if htmx {
3179        let mut response = (jar, axum::http::StatusCode::NO_CONTENT).into_response();
3180        if let Ok(value) = axum::http::HeaderValue::from_str(&to) {
3181            response.headers_mut().insert("hx-redirect", value);
3182        }
3183        return response;
3184    }
3185    (jar, Redirect::to(&to)).into_response()
3186}
3187
3188/// What the login screen says for an `ended` code. A fixed set: an unknown code
3189/// shows nothing, so nothing in the URL is ever rendered back.
3190fn end_notice(code: &str) -> Option<Text> {
3191    Some(match code {
3192        "password_changed" => {
3193            t!("Your password was changed, so you were signed out. Sign in with the new one.")
3194        }
3195        "deactivated" => t!("This account was deactivated."),
3196        "signed_out_elsewhere" => t!("You were signed out from another device."),
3197        "expired" => t!("Your session ended after a period of inactivity. Sign in again."),
3198        _ => return None,
3199    })
3200}
3201
3202/// Clears the remember cookie, for a logout or a credential that failed.
3203fn remember_removal(admin_path: &str) -> Cookie<'static> {
3204    Cookie::build((REMEMBER_COOKIE, ""))
3205        .path(admin_path.to_string())
3206        .build()
3207}
3208
3209#[derive(Deserialize)]
3210struct SetupForm {
3211    username: String,
3212    first_name: String,
3213    last_name: String,
3214    email: String,
3215    password: String,
3216    timezone: String,
3217}
3218
3219/// The first-run setup screen: shown only while no operator exists, so a fresh
3220/// install can create its first administrator without the CLI.
3221async fn setup_form(State(state): State<AdminState>, headers: HeaderMap) -> Response {
3222    match state.auth.has_any_operator().await {
3223        Ok(true) => Redirect::to(&format!("{}/login", state.admin_path)).into_response(),
3224        Ok(false) => render(setup_view(
3225            &state.admin_path,
3226            state.brand().await,
3227            state.timezone,
3228            None,
3229            pre_auth_translator(&state, &headers),
3230            state.asset_urls.clone(),
3231            state.auth.password_policy().min_length,
3232        )),
3233        Err(_) => render_error(),
3234    }
3235}
3236
3237async fn setup_submit(
3238    State(state): State<AdminState>,
3239    jar: CookieJar,
3240    headers: HeaderMap,
3241    client: Option<Extension<RequestContext>>,
3242    Form(form): Form<SetupForm>,
3243) -> Response {
3244    // Setup only ever creates the first operator; once one exists it is closed.
3245    match state.auth.has_any_operator().await {
3246        Ok(true) => return Redirect::to(&format!("{}/login", state.admin_path)).into_response(),
3247        Ok(false) => {}
3248        Err(_) => return render_error(),
3249    }
3250
3251    let username = form.username.trim();
3252    let email = form.email.trim();
3253    let first_name = form.first_name.trim();
3254    let last_name = form.last_name.trim();
3255    let tz = form.timezone.trim();
3256    if username.is_empty() || email.is_empty() || first_name.is_empty() || form.password.is_empty()
3257    {
3258        return render(setup_view(
3259            &state.admin_path,
3260            state.brand().await,
3261            state.timezone,
3262            Some(t!(
3263                "Username, first name, email, and password are all required."
3264            )),
3265            pre_auth_translator(&state, &headers),
3266            state.asset_urls.clone(),
3267            state.auth.password_policy().min_length,
3268        ));
3269    }
3270    // The setup select always carries a value, but guard against a bad one.
3271    if tz.parse::<Tz>().is_err() {
3272        return render(setup_view(
3273            &state.admin_path,
3274            state.brand().await,
3275            state.timezone,
3276            Some(t!("That is not a recognised timezone.")),
3277            pre_auth_translator(&state, &headers),
3278            state.asset_urls.clone(),
3279            state.auth.password_policy().min_length,
3280        ));
3281    }
3282
3283    let min_length = state.auth.password_policy().min_length;
3284    if form.password.chars().count() < min_length {
3285        return render(setup_view(
3286            &state.admin_path,
3287            state.brand().await,
3288            state.timezone,
3289            Some(t!(
3290                "A password needs at least {n} characters.",
3291                n = min_length as i64
3292            )),
3293            pre_auth_translator(&state, &headers),
3294            state.asset_urls.clone(),
3295            state.auth.password_policy().min_length,
3296        ));
3297    }
3298    let new = NewOperator {
3299        username,
3300        email,
3301        first_name,
3302        last_name: (!last_name.is_empty()).then_some(last_name),
3303        password: &form.password,
3304        timezone: Some(tz),
3305    };
3306    let id = match state.auth.create_superuser(new).await {
3307        Ok(id) => id,
3308        Err(_) => {
3309            return render(setup_view(
3310                &state.admin_path,
3311                state.brand().await,
3312                state.timezone,
3313                Some(t!(
3314                    "Could not create the account. The username or email may already be taken."
3315                )),
3316                pre_auth_translator(&state, &headers),
3317                state.asset_urls.clone(),
3318                state.auth.password_policy().min_length,
3319            ));
3320        }
3321    };
3322    // Nobody is signed in yet, so the trail names the process rather than an
3323    // operator, the same as a command-line action.
3324    let actor = laterite_core::Actor::system("first-run setup");
3325    let target = id.to_string();
3326    let entry = laterite_auth::AuditEntry::new(&actor, "backend.user.create").target(
3327        "backend_user",
3328        &target,
3329        Some(username),
3330    );
3331    if let Err(e) = state.auth.record_audit(entry).await {
3332        tracing::error!(error = %e, "failed to write audit log entry");
3333    }
3334
3335    // Sign the new administrator straight in through the normal login path.
3336    match state
3337        .auth
3338        .authenticate(
3339            username,
3340            &form.password,
3341            &client.map(|c| c.0).unwrap_or_default(),
3342        )
3343        .await
3344    {
3345        Ok(session) => {
3346            let cookie = session_cookie(session.token, &state.admin_path, state.secure_cookie);
3347            (jar.add(cookie), Redirect::to(&state.admin_path)).into_response()
3348        }
3349        Err(_) => Redirect::to(&format!("{}/login", state.admin_path)).into_response(),
3350    }
3351}
3352
3353/// Builds the setup view, its timezone select defaulting to the deployment
3354/// default so the first administrator can accept or change it.
3355fn setup_view(
3356    admin_path: &str,
3357    brand: String,
3358    default_tz: Tz,
3359    error: Option<Text>,
3360    i18n: Translator,
3361    asset_urls: Arc<AssetUrls>,
3362    min_password: usize,
3363) -> SetupTemplate {
3364    let default_name = default_tz.name();
3365    let zones = TZ_VARIANTS
3366        .iter()
3367        .filter(|tz| zone_offered(tz.name()))
3368        .map(|tz| TzOption {
3369            name: tz.name().to_string(),
3370            selected: tz.name() == default_name,
3371        })
3372        .collect();
3373    SetupTemplate {
3374        base: admin_path.to_string(),
3375        asset_urls,
3376        brand,
3377        zones,
3378        error: error.map(|e| i18n.t(&e)),
3379        min_password: min_password as i64,
3380        i18n,
3381    }
3382}
3383
3384async fn logout(State(state): State<AdminState>, jar: CookieJar) -> Response {
3385    if let Some(cookie) = jar.get(SESSION_COOKIE) {
3386        let _ = state.auth.logout(cookie.value()).await;
3387    }
3388    // Without this the next request would present the credential and sign
3389    // straight back in, which is not what pressing Sign out means.
3390    if let Some(cookie) = jar.get(REMEMBER_COOKIE) {
3391        let _ = state.auth.revoke_remember(cookie.value()).await;
3392    }
3393    let removal = Cookie::build((SESSION_COOKIE, ""))
3394        .path(state.admin_path.to_string())
3395        .build();
3396    (
3397        jar.remove(removal)
3398            .remove(remember_removal(&state.admin_path)),
3399        Redirect::to(&format!("{}/login", state.admin_path)),
3400    )
3401        .into_response()
3402}
3403
3404async fn dashboard(
3405    Extension(shell): Extension<Shell>,
3406    Extension(user): Extension<AuthenticatedUser>,
3407) -> Response {
3408    render(DashboardTemplate {
3409        username: user.user.username,
3410        shell,
3411    })
3412}
3413
3414/// Whether an operator may see a settings item: items with no permission are
3415/// public, otherwise the operator must hold the item's permission.
3416fn operator_can_see(item: &settings::SettingsItem, perms: &PermissionSet) -> bool {
3417    match &item.permission {
3418        None => true,
3419        Some(p) => perms.allows(p),
3420    }
3421}
3422
3423/// The settings items this operator may see, in registry order. Both the index
3424/// and the form use this set, so an operator never sees or edits an item their
3425/// permissions do not allow.
3426fn visible_settings(
3427    items: &[settings::SettingsItem],
3428    perms: &PermissionSet,
3429) -> Vec<settings::SettingsItem> {
3430    items
3431        .iter()
3432        .filter(|item| operator_can_see(item, perms))
3433        .cloned()
3434        .collect()
3435}
3436
3437async fn settings_index(Extension(shell): Extension<Shell>) -> Response {
3438    settings::index(shell)
3439}
3440
3441async fn settings_edit(
3442    state: AdminState,
3443    shell: Shell,
3444    user: AuthenticatedUser,
3445    code: String,
3446) -> Response {
3447    // Filter first, so an operator cannot open a settings form they lack the
3448    // permission to see.
3449    let items = visible_settings(&state.settings, &user.permissions);
3450    match items
3451        .iter()
3452        .find(|item| item.code == code && item.link.is_none())
3453    {
3454        Some(item) => settings::edit_form(&state, item, shell, &user).await,
3455        None => not_found(),
3456    }
3457}
3458
3459async fn settings_update(
3460    state: AdminState,
3461    shell: Shell,
3462    user: AuthenticatedUser,
3463    session: session::SessionHandle,
3464    code: String,
3465    data: HashMap<String, String>,
3466) -> Response {
3467    let items = visible_settings(&state.settings, &user.permissions);
3468    match items
3469        .iter()
3470        .find(|item| item.code == code && item.link.is_none())
3471    {
3472        Some(item) => settings::update(&state, item, data, shell, &session, &user).await,
3473        None => not_found(),
3474    }
3475}
3476
3477/// The self-service Preferences screen for the signed-in operator.
3478async fn preferences_form(
3479    State(state): State<AdminState>,
3480    Extension(shell): Extension<Shell>,
3481    Extension(user): Extension<AuthenticatedUser>,
3482    jar: CookieJar,
3483) -> Response {
3484    let account = account_security(&state, &user, &shell, &jar).await;
3485    let items: Vec<PreferenceLink> = visible_settings(&state.settings, &user.permissions)
3486        .into_iter()
3487        .filter(|i| i.per_operator)
3488        .map(|i| PreferenceLink {
3489            label: shell.tt(&i.label),
3490            description: shell.tt(&i.description),
3491            href: i.path(&state.admin_path),
3492        })
3493        .collect();
3494    render(preferences_view(
3495        &shell,
3496        &user,
3497        state.timezone,
3498        &state.default_locale,
3499        &offered_locales(&state.catalogs),
3500        account,
3501        state.auth.password_policy().min_length,
3502        items,
3503    ))
3504}
3505
3506/// A module's per-operator settings item, linked from the Preferences page.
3507struct PreferenceLink {
3508    label: String,
3509    description: String,
3510    href: String,
3511}
3512
3513#[derive(Deserialize)]
3514struct RevokeSessionForm {
3515    id: String,
3516}
3517
3518/// Ends one of the account's other sessions.
3519async fn session_revoke(
3520    State(state): State<AdminState>,
3521    Extension(user): Extension<AuthenticatedUser>,
3522    Extension(session): Extension<session::SessionHandle>,
3523    Form(form): Form<RevokeSessionForm>,
3524) -> Response {
3525    match state.auth.revoke_session(user.user.id, &form.id).await {
3526        Ok(true) => session.push_flash(FlashLevel::Success, t!("That session was signed out.")),
3527        Ok(false) => session.push_flash(FlashLevel::Info, t!("That session had already ended.")),
3528        Err(e) => {
3529            tracing::error!(error = %e, "revoking a session failed");
3530            session.push_flash(
3531                FlashLevel::Error,
3532                t!("That session could not be signed out."),
3533            );
3534        }
3535    }
3536    Redirect::to(&format!("{}/preferences", state.admin_path)).into_response()
3537}
3538
3539/// Ends every session but this one, and drops every stay-signed-in credential.
3540#[derive(Deserialize)]
3541struct MenuOrderForm {
3542    #[serde(default)]
3543    order: String,
3544}
3545
3546/// Keeps the operator's own order for the top bar (`order`: the tabs' keys,
3547/// comma-separated), or clears it when the order is blank. The drag island
3548/// posts it and takes the empty reply; the Reset button on Preferences posts
3549/// a blank and comes back to the page.
3550async fn menu_order_update(
3551    State(state): State<AdminState>,
3552    Extension(user): Extension<AuthenticatedUser>,
3553    Extension(session): Extension<session::SessionHandle>,
3554    headers: axum::http::HeaderMap,
3555    Form(form): Form<MenuOrderForm>,
3556) -> Response {
3557    let order: Vec<&str> = form
3558        .order
3559        .split(',')
3560        .map(str::trim)
3561        .filter(|k| !k.is_empty() && k.len() <= 200)
3562        .take(100)
3563        .collect();
3564    let result = if order.is_empty() {
3565        laterite_auth::store::clear_user_preference(&state.db, user.user.id, nav::ORDER_PREFERENCE)
3566            .await
3567    } else {
3568        laterite_auth::store::set_user_preference(
3569            &state.db,
3570            user.user.id,
3571            nav::ORDER_PREFERENCE,
3572            &order.join(","),
3573        )
3574        .await
3575    };
3576    if let Err(e) = result {
3577        tracing::error!(error = %e, "storing the menu order failed");
3578        return render_error();
3579    }
3580    if form::is_htmx(&headers) || headers.get("x-requested-with").is_some() {
3581        return axum::http::StatusCode::NO_CONTENT.into_response();
3582    }
3583    session.push_flash(
3584        FlashLevel::Success,
3585        if order.is_empty() {
3586            t!("The menu is back in its default order.")
3587        } else {
3588            t!("Saved.")
3589        },
3590    );
3591    Redirect::to(&format!("{}/preferences", state.admin_path)).into_response()
3592}
3593
3594async fn session_revoke_others(
3595    State(state): State<AdminState>,
3596    Extension(user): Extension<AuthenticatedUser>,
3597    Extension(session): Extension<session::SessionHandle>,
3598    jar: CookieJar,
3599) -> Response {
3600    let token = jar
3601        .get(SESSION_COOKIE)
3602        .map(|c| c.value().to_string())
3603        .unwrap_or_default();
3604    match state.auth.sign_out_everywhere(user.user.id, &token).await {
3605        Ok(_) => session.push_flash(
3606            FlashLevel::Success,
3607            t!("Every other session was signed out."),
3608        ),
3609        Err(e) => {
3610            tracing::error!(error = %e, "signing out other sessions failed");
3611            session.push_flash(
3612                FlashLevel::Error,
3613                t!("Those sessions could not be signed out."),
3614            );
3615        }
3616    }
3617    // The credential this browser holds went with the rest, so clear its cookie
3618    // rather than leave one that will fail on the next request.
3619    (
3620        jar.remove(remember_removal(&state.admin_path)),
3621        Redirect::to(&format!("{}/preferences", state.admin_path)),
3622    )
3623        .into_response()
3624}
3625
3626#[derive(Deserialize)]
3627struct PasswordForm {
3628    current_password: String,
3629    new_password: String,
3630    confirm_password: String,
3631}
3632
3633/// Changes the operator's own password. This session stays signed in, and a
3634/// stay-signed-in credential this browser holds for the account is reissued;
3635/// every other device is signed out and told why. A refusal redirects back
3636/// with its reason, so a reload never resubmits the form.
3637async fn password_update(
3638    State(state): State<AdminState>,
3639    Extension(user): Extension<AuthenticatedUser>,
3640    Extension(session): Extension<session::SessionHandle>,
3641    Extension(ctx): Extension<RequestContext>,
3642    jar: CookieJar,
3643    Form(form): Form<PasswordForm>,
3644) -> Response {
3645    let back = format!("{}/preferences#password", state.admin_path);
3646    let refuse = |message: Text| {
3647        session.push_flash(FlashLevel::Error, message);
3648        Redirect::to(&back).into_response()
3649    };
3650    if form.new_password != form.confirm_password {
3651        return refuse(t!("The new passwords do not match."));
3652    }
3653    let min_length = state.auth.password_policy().min_length;
3654    if form.new_password.chars().count() < min_length {
3655        return refuse(t!(
3656            "A password needs at least {n} characters.",
3657            n = min_length as i64
3658        ));
3659    }
3660    // Whether the stay-signed-in cookie here is this account's, asked before the
3661    // change revokes it: only then is a fresh one owed.
3662    let remembered_here = match jar.get(REMEMBER_COOKIE) {
3663        Some(cookie) => {
3664            state
3665                .auth
3666                .remember_holder(cookie.value())
3667                .await
3668                .ok()
3669                .flatten()
3670                == Some(user.user.id)
3671        }
3672        None => false,
3673    };
3674    let token = jar
3675        .get(SESSION_COOKIE)
3676        .map(|c| c.value().to_string())
3677        .unwrap_or_default();
3678    let changed = state
3679        .auth
3680        .change_own_password(
3681            user.user.id,
3682            &form.current_password,
3683            &form.new_password,
3684            &token,
3685            &ctx,
3686        )
3687        .await;
3688    match changed {
3689        Ok(()) => {}
3690        Err(laterite_auth::AuthError::InvalidCredentials) => {
3691            return refuse(t!("Your current password is not correct."));
3692        }
3693        Err(laterite_auth::AuthError::TooManyAttempts) => {
3694            return refuse(t!("Too many attempts. Try again later."));
3695        }
3696        Err(e) => {
3697            tracing::error!(error = %e, "changing a password failed");
3698            return refuse(t!("The password could not be changed."));
3699        }
3700    }
3701    session.push_flash_sticky(
3702        FlashLevel::Success,
3703        t!("Password changed. Every other device was signed out."),
3704    );
3705    let jar = if remembered_here {
3706        match state.auth.issue_remember(user.user.id).await {
3707            Ok(credential) => jar.add(remember_cookie(
3708                credential,
3709                &state.admin_path,
3710                state.secure_cookie,
3711            )),
3712            Err(e) => {
3713                tracing::error!(error = %e, "reissuing a stay-signed-in credential failed");
3714                jar.remove(remember_removal(&state.admin_path))
3715            }
3716        }
3717    } else if jar.get(REMEMBER_COOKIE).is_some() {
3718        // Not this account's, or no longer current: it would only fail on the
3719        // next request.
3720        jar.remove(remember_removal(&state.admin_path))
3721    } else {
3722        jar
3723    };
3724    (
3725        jar,
3726        Redirect::to(&format!("{}/preferences", state.admin_path)),
3727    )
3728        .into_response()
3729}
3730
3731#[derive(Deserialize)]
3732struct PreferencesForm {
3733    timezone: String,
3734    /// Omitted means no locale choice was submitted, treated as inherit.
3735    #[serde(default)]
3736    locale: String,
3737}
3738
3739async fn preferences_update(
3740    State(state): State<AdminState>,
3741    Extension(user): Extension<AuthenticatedUser>,
3742    Extension(session): Extension<session::SessionHandle>,
3743    Form(form): Form<PreferencesForm>,
3744) -> Response {
3745    let back = format!("{}/preferences", state.admin_path);
3746    let offered = offered_locales(&state.catalogs);
3747    // An empty choice clears a preference so the operator inherits the default.
3748    let tz = form.timezone.trim();
3749    let tz_stored = if tz.is_empty() {
3750        None
3751    } else if tz.parse::<Tz>().is_ok() {
3752        Some(tz)
3753    } else {
3754        session.push_flash(FlashLevel::Error, t!("That is not a recognised timezone."));
3755        return Redirect::to(&back).into_response();
3756    };
3757    let loc = form.locale.trim();
3758    let loc_stored = if loc.is_empty() {
3759        None
3760    } else if offered.iter().any(|l| l == loc) {
3761        Some(loc)
3762    } else {
3763        session.push_flash(FlashLevel::Error, t!("That is not a supported language."));
3764        return Redirect::to(&back).into_response();
3765    };
3766    if state
3767        .auth
3768        .set_user_timezone(user.user.id, tz_stored)
3769        .await
3770        .is_err()
3771    {
3772        return render_error();
3773    }
3774    match state.auth.set_user_locale(user.user.id, loc_stored).await {
3775        Ok(()) => {
3776            session.push_flash(session::FlashLevel::Success, t!("Preferences saved."));
3777            Redirect::to(&back).into_response()
3778        }
3779        Err(_) => render_error(),
3780    }
3781}
3782
3783/// Builds the Preferences view. `shell.tz` is the timezone currently in force
3784/// (the operator's preference or the default); the operator's stored preference
3785/// selects the matching option, or the inherit option when unset.
3786#[allow(clippy::too_many_arguments)]
3787fn preferences_view(
3788    shell: &Shell,
3789    user: &AuthenticatedUser,
3790    default_tz: Tz,
3791    default_locale: &str,
3792    offered: &[String],
3793    account: AccountSecurity,
3794    min_password: usize,
3795    items: Vec<PreferenceLink>,
3796) -> PreferencesTemplate {
3797    let current = user.user.timezone.as_deref();
3798    let zones = TZ_VARIANTS
3799        .iter()
3800        .filter(|tz| zone_offered(tz.name()))
3801        .map(|tz| TzOption {
3802            name: tz.name().to_string(),
3803            selected: current == Some(tz.name()),
3804        })
3805        .collect();
3806    let current_locale = user.user.locale.as_deref();
3807    let locales = offered
3808        .iter()
3809        .map(|code| LocaleOption {
3810            name: locale_name(code),
3811            selected: current_locale == Some(code.as_str()),
3812            code: code.clone(),
3813        })
3814        .collect();
3815    PreferencesTemplate {
3816        shell: shell.clone(),
3817        zones,
3818        effective_tz: shell.tz.name().to_string(),
3819        default_tz: default_tz.name().to_string(),
3820        inherits: current.is_none(),
3821        locales,
3822        default_locale: locale_name(default_locale),
3823        inherits_locale: current_locale.is_none(),
3824        sessions: account.sessions,
3825        password_changed: account.password_changed,
3826        must_change: account.must_change,
3827        min_password: min_password as i64,
3828        items,
3829    }
3830}
3831
3832/// The Preferences screen's account section: live sessions and when the
3833/// password last changed, in the operator's own timezone and locale.
3834struct AccountSecurity {
3835    sessions: Vec<SessionRow>,
3836    password_changed: Option<String>,
3837    /// The password is temporary and must be replaced before anything else.
3838    must_change: bool,
3839}
3840
3841async fn account_security(
3842    state: &AdminState,
3843    user: &AuthenticatedUser,
3844    shell: &Shell,
3845    jar: &CookieJar,
3846) -> AccountSecurity {
3847    let locale = list::date_locale(shell.locale());
3848    let password_changed = match state.auth.password_changed_at(user.user.id).await {
3849        Ok(at) => {
3850            at.map(|dt| list::format_ts(&dt.to_rfc3339(), shell.tz, locale, "%-d %b %Y, %H:%M"))
3851        }
3852        Err(e) => {
3853            tracing::error!(error = %e, "reading the password change time failed");
3854            None
3855        }
3856    };
3857    AccountSecurity {
3858        sessions: session_rows(state, user, shell, jar).await,
3859        password_changed,
3860        must_change: state
3861            .auth
3862            .must_change_password(user.user.id)
3863            .await
3864            .unwrap_or(false),
3865    }
3866}
3867
3868/// Reads the account's live sessions and formats them in the operator's own
3869/// timezone and locale, the same way list columns render a timestamp.
3870async fn session_rows(
3871    state: &AdminState,
3872    user: &AuthenticatedUser,
3873    shell: &Shell,
3874    jar: &CookieJar,
3875) -> Vec<SessionRow> {
3876    let token = jar
3877        .get(SESSION_COOKIE)
3878        .map(|c| c.value().to_string())
3879        .unwrap_or_default();
3880    let locale = list::date_locale(shell.locale());
3881    let stamp = |dt: chrono::DateTime<chrono::Utc>| {
3882        list::format_ts(&dt.to_rfc3339(), shell.tz, locale, "%-d %b %Y, %H:%M")
3883    };
3884    match state.auth.list_sessions(user.user.id, &token).await {
3885        Ok(sessions) => sessions
3886            .into_iter()
3887            .map(|s| SessionRow {
3888                id: s.id,
3889                started: stamp(s.created_at),
3890                last_seen: stamp(s.last_seen_at),
3891                expires: stamp(s.expires_at),
3892                device: clientip::describe(s.user_agent.as_deref())
3893                    .or(s.user_agent)
3894                    .unwrap_or_else(|| "-".to_string()),
3895                ip_address: s.ip_address.unwrap_or_default(),
3896                current: s.current,
3897            })
3898            .collect(),
3899        Err(e) => {
3900            tracing::error!(error = %e, "listing sessions failed");
3901            Vec::new()
3902        }
3903    }
3904}
3905
3906/// The framework's own admin screens.
3907fn builtin_resources() -> Vec<Resource> {
3908    vec![
3909        Resource {
3910            base_path: "/users".to_string(),
3911            nav_label: "Administrators".into(),
3912            list: backend_users_list_config(),
3913            form: None,
3914            permission: Some("backend.manage_users".to_string()),
3915            import: None,
3916            palette: None,
3917            relations: Vec::new(),
3918            menu: nav::Placement::default(),
3919        },
3920        Resource {
3921            base_path: "/roles".to_string(),
3922            nav_label: "Roles".into(),
3923            list: roles_list_config(),
3924            // The create/edit form is the dedicated permission editor (see the
3925            // `roles` module), mounted separately, not the generic form.
3926            form: None,
3927            permission: Some("backend.manage_roles".to_string()),
3928            import: None,
3929            palette: None,
3930            relations: Vec::new(),
3931            menu: nav::Placement::default(),
3932        },
3933        resource!("descriptors/audit-log.yaml"),
3934        resource!("descriptors/access-log.yaml"),
3935        resource!("descriptors/request-log.yaml"),
3936    ]
3937}
3938
3939/// The framework's own settings items. The built-in Users and Roles resources
3940/// appear in the settings menu under a Users category (linking to their list
3941/// screens), rather than as main-menu tabs.
3942fn builtin_settings() -> Vec<settings::SettingsItem> {
3943    vec![
3944        settings::SettingsItem::new("backend.administrators", "Administrators", Vec::new())
3945            .description("Manage backend administrator accounts.")
3946            .category("Users")
3947            .order(10)
3948            .icon("users")
3949            .permission("backend.manage_users")
3950            .link("/users"),
3951        settings::SettingsItem::new("backend.roles", "Roles", Vec::new())
3952            .description("Manage roles and their permissions.")
3953            .category("Users")
3954            .order(20)
3955            .icon("shield")
3956            .permission("backend.manage_roles")
3957            .link("/roles"),
3958        settings::brand::settings_item(),
3959        settings::SettingsItem::new("backend.plugins", "Plugins", Vec::new())
3960            .description("Enable or disable installed plugins.")
3961            .category("System")
3962            .order(10)
3963            .icon("plug")
3964            .permission(plugins::MANAGE_PERMISSION)
3965            .link("/plugins"),
3966        settings::SettingsItem::new("backend.audit_log", "Audit Log", Vec::new())
3967            .description("Review the record of administrative changes.")
3968            .category("System")
3969            .order(20)
3970            .icon("history")
3971            .permission("backend.view_audit_log")
3972            .link("/audit-log"),
3973        settings::SettingsItem::new("backend.access_log", "Access Log", Vec::new())
3974            .description("Review sign-ins, failures and lockouts.")
3975            .category("System")
3976            .order(30)
3977            .icon("log-in")
3978            .permission("backend.view_access_log")
3979            .link("/access-log"),
3980        settings::SettingsItem::new("backend.request_log", "Request Log", Vec::new())
3981            .description("Review the URLs the panel could not serve.")
3982            .category("System")
3983            .order(31)
3984            .icon("unlink")
3985            .permission("backend.view_request_log")
3986            .link("/request-log"),
3987    ]
3988}
3989
3990fn backend_users_list_config() -> list::ListConfig {
3991    list::ListConfig {
3992        entity: "backend_users".to_string(),
3993        title: "Administrators".into(),
3994        columns: vec![
3995            list::ListColumn::new("username", "Username"),
3996            list::ListColumn::new("email", "Email"),
3997            list::ListColumn::new("first_name", "First name"),
3998            list::ListColumn::new("last_name", "Last name"),
3999            list::ListColumn::new("is_superuser", "Superuser").yes_no(),
4000            list::ListColumn::new("is_active", "Active").yes_no(),
4001            list::ListColumn::new("created_at", "Created").datetime(),
4002        ],
4003        order_by: "created_at".to_string(),
4004        // Rows link to the per-user editor; New creates an account with a
4005        // temporary password.
4006        creatable: true,
4007        edit_base: Some("/users".to_string()),
4008        filters: vec![
4009            list::ListFilter::boolean("is_active", "Active"),
4010            list::ListFilter::boolean("is_superuser", "Superuser"),
4011        ],
4012        // Removing an operator from a list is too easy to do by accident;
4013        // deactivating is the reversible equivalent and is what the filter above
4014        // is for.
4015        ..Default::default()
4016    }
4017}
4018
4019fn roles_list_config() -> list::ListConfig {
4020    list::ListConfig {
4021        entity: "backend_roles".to_string(),
4022        title: "Roles".into(),
4023        columns: vec![
4024            list::ListColumn::new("code", "Code"),
4025            list::ListColumn::new("name", "Name"),
4026            list::ListColumn::new("created_at", "Created").datetime(),
4027        ],
4028        order_by: "created_at".to_string(),
4029        edit_base: Some("/roles".to_string()),
4030        creatable: true,
4031        deletable: true,
4032        ..Default::default()
4033    }
4034}
4035
4036#[derive(Template)]
4037#[template(path = "login.html")]
4038struct LoginTemplate {
4039    /// The admin mount path, so pre-auth asset and form URLs match the panel.
4040    base: String,
4041    /// Each asset's content-named path; see [`Shell::asset`].
4042    asset_urls: Arc<AssetUrls>,
4043    brand: String,
4044    error: Option<String>,
4045    /// Why the previous session ended, when the redirect said.
4046    notice: Option<String>,
4047    /// The pre-auth translator (config locale, then `Accept-Language`); no operator
4048    /// preference exists yet. `self.t` and `self.locale` localize this screen.
4049    i18n: Translator,
4050}
4051
4052/// Builds a content-named asset URL for the pre-auth screens, which render
4053/// before a [`Shell`] exists and so carry the map themselves.
4054fn preauth_asset(urls: &AssetUrls, base: &str, key: &str) -> String {
4055    match urls.get(key) {
4056        Some(path) => format!("{base}/assets/{path}"),
4057        None => {
4058            debug_assert!(false, "asset key `{key}` is not registered");
4059            format!("{base}/assets/{key}")
4060        }
4061    }
4062}
4063
4064impl LoginTemplate {
4065    fn asset(&self, key: &str) -> String {
4066        preauth_asset(&self.asset_urls, &self.base, key)
4067    }
4068    fn t(&self, source: &str) -> String {
4069        self.i18n.t(&Text::dynamic(source))
4070    }
4071    fn locale(&self) -> &str {
4072        self.i18n.locale()
4073    }
4074}
4075
4076#[derive(Template)]
4077#[template(path = "dashboard.html")]
4078struct DashboardTemplate {
4079    shell: Shell,
4080    username: String,
4081}
4082
4083#[derive(Template)]
4084#[template(path = "setup.html")]
4085struct SetupTemplate {
4086    /// The admin mount path, so pre-auth asset and form URLs match the panel.
4087    base: String,
4088    /// Each asset's content-named path; see [`Shell::asset`].
4089    asset_urls: Arc<AssetUrls>,
4090    brand: String,
4091    zones: Vec<TzOption>,
4092    error: Option<String>,
4093    /// The pre-auth translator, as on [`LoginTemplate`].
4094    i18n: Translator,
4095    /// The shortest password the policy accepts.
4096    min_password: i64,
4097}
4098
4099impl SetupTemplate {
4100    /// Localizes a source string with integer `{name}` arguments, as
4101    /// [`Shell::tf`] does for signed-in screens.
4102    fn tf(&self, source: &str, args: &[(&'static str, i64)]) -> String {
4103        let mut text = Text::dynamic(source);
4104        for (name, value) in args {
4105            text = text.arg(*name, *value);
4106        }
4107        self.i18n.t(&text)
4108    }
4109
4110    fn asset(&self, key: &str) -> String {
4111        preauth_asset(&self.asset_urls, &self.base, key)
4112    }
4113    fn t(&self, source: &str) -> String {
4114        self.i18n.t(&Text::dynamic(source))
4115    }
4116    fn locale(&self) -> &str {
4117        self.i18n.locale()
4118    }
4119}
4120
4121#[derive(Template)]
4122#[template(path = "preferences.html")]
4123struct PreferencesTemplate {
4124    shell: Shell,
4125    zones: Vec<TzOption>,
4126    /// The timezone dates currently render in for this operator.
4127    effective_tz: String,
4128    /// The deployment default, named in the inherit option.
4129    default_tz: String,
4130    /// Whether the operator currently inherits the default (no preference set).
4131    inherits: bool,
4132    locales: Vec<LocaleOption>,
4133    /// The deployment default locale, named in the inherit option.
4134    default_locale: String,
4135    /// Whether the operator currently inherits the default locale.
4136    inherits_locale: bool,
4137    /// The account's live sessions, most recently active first.
4138    sessions: Vec<SessionRow>,
4139    /// When the password last changed, formatted; `None` when not recorded.
4140    password_changed: Option<String>,
4141    /// The password is temporary; nothing else opens until it is replaced.
4142    must_change: bool,
4143    /// The shortest password accepted, for the form's help and `minlength`.
4144    min_password: i64,
4145    /// Modules' per-operator settings, each a page of its own.
4146    items: Vec<PreferenceLink>,
4147}
4148
4149/// One of the account's live sessions, formatted for the page.
4150struct SessionRow {
4151    id: String,
4152    started: String,
4153    last_seen: String,
4154    expires: String,
4155    /// "Chrome on macOS", or the raw agent when it is not one we name, or a
4156    /// dash when the request carried none.
4157    device: String,
4158    /// Where it signed in from, blank when the deployment records no address.
4159    ip_address: String,
4160    current: bool,
4161}
4162
4163struct TzOption {
4164    name: String,
4165    selected: bool,
4166}
4167
4168struct LocaleOption {
4169    /// The base language tag (`en`, `kn`).
4170    code: String,
4171    /// The language's own name, shown untranslated.
4172    name: String,
4173    selected: bool,
4174}
4175
4176/// One step of the way to the current page.
4177#[derive(Clone)]
4178struct CrumbView {
4179    label: String,
4180    href: String,
4181}
4182
4183#[derive(Clone)]
4184struct NavView {
4185    /// The item's key, which the operator's own order names.
4186    key: String,
4187    label: String,
4188    path: String,
4189    active: bool,
4190    /// Inline SVG for the tab's icon, or empty for a text-only tab. Rendered raw
4191    /// with `|safe`.
4192    icon: String,
4193}
4194
4195/// Renders a template to an HTML response, mapping a render failure to a 500.
4196pub(crate) fn render<T: Template>(template: T) -> Response {
4197    match template.render() {
4198        Ok(html) => Html(html).into_response(),
4199        // A render failure is unexpected: log the cause via AdminError, then mask.
4200        Err(e) => AdminError::from(e).into_response(),
4201    }
4202}
4203
4204pub(crate) fn render_error() -> Response {
4205    error::masked_500()
4206}
4207
4208pub(crate) fn not_found() -> Response {
4209    AdminError::NotFound.into_response()
4210}
4211
4212pub(crate) fn forbidden() -> Response {
4213    AdminError::Forbidden.into_response()
4214}
4215
4216#[cfg(test)]
4217mod tests {
4218    use super::*;
4219
4220    fn write_form() -> form::FormConfig {
4221        form::FormConfig {
4222            enter: Default::default(),
4223            confirm_leave: true,
4224            focus: Default::default(),
4225            entity: "widgets".to_string(),
4226            title: "Widgets".into(),
4227            base_path: "/widgets".to_string(),
4228            id_field: "id".to_string(),
4229            fields: vec![],
4230            persist: None,
4231            timestamps: false,
4232            done_path: None,
4233        }
4234    }
4235
4236    fn resource_with(form: Option<form::FormConfig>, permission: Option<&str>) -> Resource {
4237        Resource {
4238            base_path: "/widgets".to_string(),
4239            nav_label: "Widgets".into(),
4240            list: backend_users_list_config(),
4241            form,
4242            permission: permission.map(str::to_string),
4243            import: None,
4244            palette: None,
4245            relations: Vec::new(),
4246            menu: nav::Placement::default(),
4247        }
4248    }
4249
4250    #[test]
4251    #[should_panic(expected = "must declare a permission")]
4252    fn write_resource_without_permission_aborts_boot() {
4253        // A create/edit form with no permission would expose its mutations to any
4254        // signed-in operator; mounting it aborts boot.
4255        let resource = resource_with(Some(write_form()), None);
4256        let _ = mount_resource(
4257            &resource,
4258            &field::builtin_registry(),
4259            &list::builtin_column_registry(),
4260            &std::collections::HashSet::new(),
4261            &persist::PersisterRegistry::new(),
4262            &[],
4263        );
4264    }
4265
4266    /// The access log is a descriptor file too, pinned the same way.
4267    #[test]
4268    fn the_access_log_is_read_from_its_descriptor_file() {
4269        let access = builtin_resources()
4270            .into_iter()
4271            .find(|r| r.base_path == "/access-log")
4272            .expect("the access log is registered");
4273        assert_eq!(access.list.entity, "backend_access_log");
4274        assert_eq!(
4275            access.permission.as_deref(),
4276            Some("backend.view_access_log")
4277        );
4278        assert!(access.form.is_none(), "append-only");
4279        assert_eq!(
4280            access
4281                .list
4282                .columns
4283                .iter()
4284                .map(|c| c.field.as_str())
4285                .collect::<Vec<_>>(),
4286            [
4287                "created_at",
4288                "username_attempted",
4289                "event",
4290                "ip_address",
4291                "user_agent"
4292            ]
4293        );
4294    }
4295
4296    /// The audit log is a descriptor file. Its shape is pinned here, so the
4297    /// file and the screen cannot drift apart unnoticed.
4298    #[test]
4299    fn the_audit_log_is_read_from_its_descriptor_file() {
4300        let audit = builtin_resources()
4301            .into_iter()
4302            .find(|r| r.base_path == "/audit-log")
4303            .expect("the audit log is registered");
4304        assert_eq!(audit.list.entity, "backend_audit_log");
4305        assert_eq!(audit.permission.as_deref(), Some("backend.view_audit_log"));
4306        assert_eq!(
4307            audit
4308                .list
4309                .columns
4310                .iter()
4311                .map(|c| c.field.as_str())
4312                .collect::<Vec<_>>(),
4313            [
4314                "created_at",
4315                "actor_username",
4316                "action",
4317                "target_type",
4318                "target_id",
4319                "target_label"
4320            ],
4321            "in the order the file writes them"
4322        );
4323        assert_eq!(audit.list.columns[0].column_type, "datetime");
4324        assert_eq!(audit.list.per_page, 50);
4325        assert_eq!(audit.list.per_page_options, [25, 50, 100]);
4326        assert!(audit.list.exportable, "evidence may leave the panel");
4327        assert!(audit.form.is_none(), "append-only: no form");
4328        assert!(!audit.list.deletable, "and nothing removes from it");
4329    }
4330
4331    #[test]
4332    #[should_panic(expected = "uses unregistered type `nope`")]
4333    fn unregistered_column_type_aborts_boot() {
4334        let mut resource = resource_with(None, None);
4335        let mut score = list::ListColumn::new("score", "Score");
4336        score.column_type = "nope".into();
4337        resource.list.columns.push(score);
4338        let _ = mount_resource(
4339            &resource,
4340            &field::builtin_registry(),
4341            &list::builtin_column_registry(),
4342            &std::collections::HashSet::new(),
4343            &persist::PersisterRegistry::new(),
4344            &[],
4345        );
4346    }
4347
4348    #[test]
4349    fn read_only_resource_may_omit_permission() {
4350        // No write path, so no permission is required: this mounts without panicking.
4351        let resource = resource_with(None, None);
4352        let _ = mount_resource(
4353            &resource,
4354            &field::builtin_registry(),
4355            &list::builtin_column_registry(),
4356            &std::collections::HashSet::new(),
4357            &persist::PersisterRegistry::new(),
4358            &[],
4359        );
4360    }
4361
4362    #[test]
4363    fn shell_localizes_through_the_translator_and_falls_back() {
4364        // The default translator has no catalog, so each source returns itself.
4365        let shell = Shell::test();
4366        assert_eq!(shell.t("Save"), "Save");
4367        assert_eq!(shell.tt(&Text::dynamic("Discard")), "Discard");
4368    }
4369
4370    #[test]
4371    fn shell_tf_interpolates_integer_arguments() {
4372        let shell = Shell::test();
4373        assert_eq!(
4374            shell.tf("Page {page} of {pages}", &[("page", 2), ("pages", 5)]),
4375            "Page 2 of 5"
4376        );
4377    }
4378
4379    #[test]
4380    fn display_tz_prefers_a_valid_operator_preference() {
4381        assert_eq!(
4382            resolve_display_tz(Some("Asia/Kolkata"), Tz::UTC),
4383            Tz::Asia__Kolkata
4384        );
4385    }
4386
4387    #[test]
4388    fn display_tz_falls_back_when_unset_or_invalid() {
4389        let default = Tz::Europe__London;
4390        // No preference: use the deployment default.
4391        assert_eq!(resolve_display_tz(None, default), default);
4392        // Junk stored value: fall back rather than error.
4393        assert_eq!(resolve_display_tz(Some("Not/AZone"), default), default);
4394        assert_eq!(resolve_display_tz(Some(""), default), default);
4395    }
4396
4397    #[test]
4398    fn accept_language_orders_by_weight_and_drops_wildcard() {
4399        assert_eq!(
4400            parse_accept_language("en-US,en;q=0.9,kn;q=0.8"),
4401            vec!["en-US", "en", "kn"]
4402        );
4403        // A higher-weight later tag wins; the wildcard is dropped.
4404        assert_eq!(
4405            parse_accept_language("en;q=0.5,kn,*;q=0.1"),
4406            vec!["kn", "en"]
4407        );
4408    }
4409
4410    #[test]
4411    fn locale_chain_prefers_operator_then_header_then_default() {
4412        // A deployment with hi/kn/ta catalogs loaded (en is always serveable).
4413        let loaded = ["hi".to_string(), "kn".to_string(), "ta".to_string()];
4414        // Operator preference leads, then header order, then the default; en is
4415        // appended last as the source fallback, and nothing repeats.
4416        assert_eq!(
4417            resolve_locale_chain(Some("kn"), Some("ta;q=0.9,hi;q=0.8"), "en", &loaded),
4418            vec!["kn", "ta", "hi", "en"]
4419        );
4420        // An explicit en in the header keeps its signaled position, not forced last.
4421        assert_eq!(
4422            resolve_locale_chain(Some("kn"), Some("en;q=0.9"), "ta", &loaded),
4423            vec!["kn", "en", "ta"]
4424        );
4425        // A regional tag normalizes to its base language.
4426        assert_eq!(
4427            resolve_locale_chain(Some("kn-IN"), None, "en", &loaded),
4428            vec!["kn", "en"]
4429        );
4430    }
4431
4432    #[test]
4433    fn locale_chain_skips_unserveable_and_defaults_to_en() {
4434        // Only hi has a catalog here; en is always serveable.
4435        let loaded = ["hi".to_string()];
4436        // Tags with no loaded catalog (and not en) are skipped; an unserveable
4437        // default falls to en, leaving just the source.
4438        assert_eq!(
4439            resolve_locale_chain(Some("fr"), Some("de,es"), "zz", &loaded),
4440            vec!["en"]
4441        );
4442        // No signal at all is still a valid en chain.
4443        assert_eq!(resolve_locale_chain(None, None, "en", &loaded), vec!["en"]);
4444        // A loaded catalog makes its locale serveable with no other change.
4445        assert_eq!(
4446            resolve_locale_chain(Some("hi"), None, "en", &loaded),
4447            vec!["hi", "en"]
4448        );
4449        // The pseudo-locale resolves without a catalog (QA selects it explicitly).
4450        assert_eq!(
4451            resolve_locale_chain(Some(laterite_core::PSEUDO_LOCALE), None, "en", &loaded),
4452            vec![laterite_core::PSEUDO_LOCALE, "en"]
4453        );
4454    }
4455
4456    #[test]
4457    fn page_assets_dedupe_preserve_order_and_classify() {
4458        let mut reg = AssetRegistry::new();
4459        reg.insert(
4460            "a.js",
4461            AdminAsset {
4462                mime: "text/javascript; charset=utf-8",
4463                bytes: std::borrow::Cow::Borrowed(b"//"),
4464            },
4465        );
4466        reg.insert(
4467            "b.css",
4468            AdminAsset {
4469                mime: "text/css; charset=utf-8",
4470                bytes: std::borrow::Cow::Borrowed(b"body{}"),
4471            },
4472        );
4473        // A repeated key collapses to one, keeping first-seen order; the URL is
4474        // built from the base and names the content; css-vs-js follows the mime.
4475        let urls = asset_urls(&reg);
4476        let assets = page_assets(&["a.js", "b.css", "a.js"], "/admin", &reg, &urls);
4477        assert_eq!(assets.len(), 2);
4478        assert_eq!(
4479            assets[0].url,
4480            format!("/admin/assets/a.{}.js", http_cache::digest(b"//"))
4481        );
4482        assert!(!assets[0].css);
4483        assert_eq!(
4484            assets[1].url,
4485            format!("/admin/assets/b.{}.css", http_cache::digest(b"body{}"))
4486        );
4487        assert!(assets[1].css);
4488        // Different bytes must produce different URLs, which is the whole
4489        // reason these may be served as immutable.
4490        assert_ne!(assets[0].url, assets[1].url);
4491    }
4492
4493    /// A fresh test database with no migrations applied, the blank slate an
4494    /// application starts from before it runs its migration set. Hold the guard
4495    /// for the test's lifetime.
4496    async fn empty_db() -> (Db, laterite_core::testing::TestGuard) {
4497        laterite_core::testing::connect_test(&[]).await
4498    }
4499
4500    #[tokio::test]
4501    async fn builtin_migrations_create_the_admin_tables() {
4502        let (db, _guard) = empty_db().await;
4503        laterite_core::migration::run(&db.pool, db.backend, &builtin_migrations())
4504            .await
4505            .unwrap();
4506        // A table from each bundled module exists, so an app that only ran
4507        // builtin_migrations has everything the admin's screens need. A no-row
4508        // probe succeeds only if the table exists, portably on every backend.
4509        for table in ["backend_users", "settings"] {
4510            let probe = sqlx::query(&format!("select 1 from {table} where 1 = 0"))
4511                .fetch_optional(&db.pool)
4512                .await;
4513            assert!(
4514                probe.is_ok(),
4515                "{table} should exist after builtin_migrations"
4516            );
4517        }
4518    }
4519
4520    #[tokio::test]
4521    async fn brand_setting_overrides_config_and_blank_falls_back() {
4522        let (db, _guard) = laterite_core::testing::connect_test(&[settings::migrations()]).await;
4523        let state = AdminState {
4524            auth: AuthService::new(db.clone(), laterite_auth::AuthConfig::default()),
4525            db: db.clone(),
4526            nav: Arc::new(nav::NavTree::default()),
4527            settings: Arc::new(Vec::new()),
4528            permissions: Arc::new(builtin_permissions()),
4529            trusted_proxies: Arc::new(Vec::new()),
4530            icons: Arc::new(laterite_core::icons::IconSet::new()),
4531            sprite_url: Arc::from(""),
4532            admin_path: Arc::from("/admin"),
4533            secure_cookie: false,
4534            origin: Arc::from(""),
4535            timezone: Tz::UTC,
4536            default_locale: Arc::from("en"),
4537            catalogs: Arc::new(CatalogStore::default()),
4538            app_name: "Configured Name".to_string(),
4539            brand_cache: Arc::new(RwLock::new(None)),
4540            field_types: Arc::new(field::builtin_registry()),
4541            column_types: Arc::new(list::builtin_column_registry()),
4542            plugin_defined: Arc::new(laterite_core::Registry::new()),
4543            assets: Arc::new(builtin_assets()),
4544            asset_urls: Arc::new(asset_urls(&builtin_assets())),
4545            pickers: Arc::new(picker::PickerRegistry::new()),
4546            palette: Arc::new(Vec::new()),
4547            overrides: Arc::new(field::NoOverrides),
4548        };
4549
4550        // With no brand setting, the configured application name is the brand.
4551        assert_eq!(state.brand().await, "Configured Name");
4552
4553        // A brand setting overrides the configured name (cache re-reads after
4554        // invalidation).
4555        settings::store::save(
4556            &db,
4557            &settings::BrandSetting {
4558                app_name: "Acme Corp".to_string(),
4559            },
4560        )
4561        .await
4562        .unwrap();
4563        state.invalidate_brand();
4564        assert_eq!(state.brand().await, "Acme Corp");
4565
4566        // A blank brand setting falls back to the configured name.
4567        settings::store::save(
4568            &db,
4569            &settings::BrandSetting {
4570                app_name: "   ".to_string(),
4571            },
4572        )
4573        .await
4574        .unwrap();
4575        state.invalidate_brand();
4576        assert_eq!(state.brand().await, "Configured Name");
4577    }
4578
4579    fn settings_item(code: &str, permission: Option<&str>) -> settings::SettingsItem {
4580        settings::SettingsItem {
4581            code: code.to_string(),
4582            label: code.into(),
4583            description: String::new().into(),
4584            category: "General".into(),
4585            hint: None,
4586            confirm_leave: true,
4587            order: 1,
4588            icon: None,
4589            permission: permission.map(str::to_string),
4590            link: None,
4591            fields: Vec::new(),
4592            route: None,
4593            per_operator: false,
4594        }
4595    }
4596
4597    #[test]
4598    fn settings_visibility_respects_permissions() {
4599        let items = vec![
4600            settings_item("public", None),
4601            settings_item("gated", Some("backend.manage_users")),
4602        ];
4603
4604        // An operator without the grant sees only the unpermissioned item.
4605        let none = PermissionSet::new(false, Vec::<String>::new());
4606        let codes: Vec<String> = visible_settings(&items, &none)
4607            .into_iter()
4608            .map(|i| i.code)
4609            .collect();
4610        assert_eq!(codes, ["public"]);
4611
4612        // Holding the permission reveals the gated item.
4613        let granted = PermissionSet::new(false, ["backend.manage_users".to_string()]);
4614        assert_eq!(visible_settings(&items, &granted).len(), 2);
4615
4616        // A superuser sees everything.
4617        let superuser = PermissionSet::new(true, Vec::<String>::new());
4618        assert_eq!(visible_settings(&items, &superuser).len(), 2);
4619    }
4620
4621    #[test]
4622    fn context_sidebar_follows_settings_links() {
4623        let items = builtin_settings();
4624        let superuser = PermissionSet::new(true, Vec::<String>::new());
4625        let tr = Translator::new("en");
4626        let tree = nav::NavTree::default();
4627        let sidebar = |path: &str| {
4628            resolve_nav_context(
4629                &tree,
4630                &items,
4631                "/admin",
4632                &superuser,
4633                None,
4634                path,
4635                &tr,
4636                icons::Icons::new(&laterite_core::icons::IconSet::new(), "/s.svg"),
4637            )
4638            .1
4639        };
4640        let active_path = |path: &str| -> Option<String> {
4641            sidebar(path)
4642                .into_iter()
4643                .flat_map(|g| g.items)
4644                .find(|i| i.active)
4645                .map(|i| i.path)
4646        };
4647
4648        // A linked resource, and its sub-pages, resolve to that item as active.
4649        assert_eq!(active_path("/admin/users").as_deref(), Some("/admin/users"));
4650        assert_eq!(
4651            active_path("/admin/roles/42/edit").as_deref(),
4652            Some("/admin/roles")
4653        );
4654        // The settings index shows the sidebar, with nothing active.
4655        assert!(!sidebar("/admin/settings").is_empty());
4656        assert_eq!(active_path("/admin/settings"), None);
4657        // A settings screen of the item's own activates that item. Branding is
4658        // the framework's one form-backed setting; unresolved in this test, it
4659        // falls back to a path built from its code's segments, which is a URL
4660        // rather than the dotted storage key it used to be.
4661        assert_eq!(
4662            active_path("/admin/settings/branding").as_deref(),
4663            Some("/admin/settings/branding")
4664        );
4665        // The dotted storage key is not a path at all any more, and neither is
4666        // the vendor-qualified form: the panel's own settings carry no vendor.
4667        assert_eq!(active_path("/admin/settings/laterite.brand"), None);
4668        assert_eq!(active_path("/admin/settings/laterite/brand"), None);
4669        // The dashboard is not a settings context, so it has no sidebar.
4670        assert!(sidebar("/admin").is_empty());
4671    }
4672}
4673
4674#[cfg(test)]
4675mod session_cookie_tests {
4676    use super::*;
4677
4678    /// The session cookie always dies with the browser. Persistence belongs to
4679    /// the remember credential, which can be rotated and revoked on its own; a
4680    /// long-lived session cookie could be neither.
4681    #[test]
4682    fn the_session_cookie_never_outlives_the_browser() {
4683        let cookie = session_cookie("tok".into(), "/admin", false);
4684        assert_eq!(cookie.max_age(), None);
4685        assert!(cookie.http_only().unwrap_or(false));
4686        assert_eq!(cookie.path(), Some("/admin"));
4687    }
4688
4689    /// "Stay signed in" is what survives a closed browser, and it carries its
4690    /// own lifetime rather than borrowing the session's.
4691    #[test]
4692    fn the_remember_cookie_carries_its_own_lifetime() {
4693        let credential = laterite_auth::RememberCredential {
4694            cookie: "sel:ver".into(),
4695            expires_at: chrono::Utc::now() + chrono::Duration::days(14),
4696        };
4697        let cookie = remember_cookie(credential, "/admin", true);
4698        let age = cookie.max_age().expect("a remember cookie must persist");
4699        // Within a second of fourteen days, allowing for the clock read.
4700        assert!((age.whole_seconds() - 14 * 24 * 60 * 60).abs() <= 1);
4701        assert!(cookie.http_only().unwrap_or(false));
4702        assert!(cookie.secure().unwrap_or(false));
4703    }
4704
4705    /// Clearing has to match on path or the browser keeps the original.
4706    #[test]
4707    fn the_removal_matches_the_cookie_it_clears() {
4708        let removal = remember_removal("/admin");
4709        assert_eq!(removal.name(), REMEMBER_COOKIE);
4710        assert_eq!(removal.path(), Some("/admin"));
4711    }
4712}