Skip to main content

laterite_admin/
lib.rs

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