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