//! `/admin/settings`: the policy values that an administrator can change without a restart. //! //! Each value comes from one of three places, and the page shows which: a value saved here (`UI`), the //! configuration file (`file`), or the built-in default. A saved value is a `policy.` setting; it wins //! over the file. Reset removes the saved value, so the file value applies again. Every value is checked //! with the same rules as the file before anything is written, so a bad form changes nothing. //! //! The file-only settings (base address, listen address, database, data directory, trusted proxies) are shown //! read-only: they are used when the server starts, so changing them here would do nothing until a restart. use im_core::config::{POLICY_KEYS, PolicyConfig}; use im_core::model::AuditAction; use serde::Deserialize; use serde_json::json; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::error::{SeeOther, not_found}; use topcoat::router::{page, route}; use topcoat::view::{View, component, view}; use crate::audit::{Actor, record}; use crate::auth::{require_admin, require_admin_csrf}; use crate::boot::{effective_policy, merge_saved_policy}; use crate::i18n::Lang; use crate::i18n::admin::{A, text}; use crate::pages::admin::{ FlashQuery, Tab, changed, done, error_text, flash_messages, frame_info, notice_text, refused, tabs, }; use crate::state::AppState; use crate::views::{ViewerInfo, shell}; /// The form of the settings: one text field per policy key, and the CSRF token. #[derive(Deserialize, Default)] struct SettingsForm { #[serde(default)] csrf: String, #[serde(default)] require_2fa_for_admins: String, #[serde(default)] max_sessions: String, #[serde(default)] session_max_days: String, #[serde(default)] invite_days: String, #[serde(default)] reset_minutes: String, #[serde(default)] email_change_hours: String, } impl SettingsForm { /// Each key with the value typed for it, in the order of `POLICY_KEYS`. fn values(&self) -> [(&'static str, &str); 6] { [ ("require_2fa_for_admins", &self.require_2fa_for_admins), ("max_sessions", &self.max_sessions), ("session_max_days", &self.session_max_days), ("invite_days", &self.invite_days), ("reset_minutes", &self.reset_minutes), ("email_change_hours", &self.email_change_hours), ] } } /// The form of a reset: the key to reset, and the CSRF token. #[derive(Deserialize, Default)] struct ResetForm { #[serde(default)] csrf: String, #[serde(default)] key: String, } /// The value of one policy key as text, the way the form shows and accepts it. fn value_of(policy: &PolicyConfig, key: &str) -> String { match key { "require_2fa_for_admins" => policy.require_2fa_for_admins.to_string(), "max_sessions" => policy.max_sessions.to_string(), "session_max_days" => policy.session_max_days.to_string(), "invite_days" => policy.invite_days.to_string(), "reset_minutes" => policy.reset_minutes.to_string(), "email_change_hours" => policy.email_change_hours.to_string(), _ => String::new(), } } /// The labels and hints of a policy key. fn labels(key: &str) -> (A, A) { match key { "require_2fa_for_admins" => (A::SettingLabelRequire2fa, A::SettingHintRequire2fa), "max_sessions" => (A::SettingLabelMaxSessions, A::SettingHintMaxSessions), "session_max_days" => (A::SettingLabelSessionDays, A::SettingHintSessionDays), "invite_days" => (A::SettingLabelInviteDays, A::SettingHintInviteDays), "reset_minutes" => (A::SettingLabelResetMinutes, A::SettingHintResetMinutes), _ => (A::SettingLabelEmailHours, A::SettingHintEmailHours), } } /// One row of the settings table: the key, its value now, and where the value comes from. struct SettingRow { key: &'static str, value: String, source: Source, } /// Where a policy value comes from. #[derive(Clone, Copy, PartialEq, Eq)] enum Source { Ui, File, Default, } /// `GET /admin/settings`. #[page("/admin/settings")] async fn settings_page(cx: &Cx, Form(query): Form) -> Result { let viewer = require_admin(cx).await?; let state = app_context::(cx); let (lang, info) = frame_info(cx, &viewer); let policy = state.policy(); let saved: Vec = state .store .settings_with_prefix("policy.") .await? .into_iter() .map(|(key, _)| key.trim_start_matches("policy.").to_owned()) .collect(); let rows: Vec = POLICY_KEYS .iter() .map(|key| SettingRow { key, value: value_of(&policy, key), source: if saved.iter().any(|name| name == key) { Source::Ui } else if state.config.explicit_policy.iter().any(|name| name == key) { Source::File } else { Source::Default }, }) .collect(); let file = FileValues { base_url: state.config.base_url.clone(), listen: state.config.listen.to_string(), database: state.config.database.display().to_string(), data_dir: state.config.data_dir.display().to_string(), trusted_proxies: state .config .trusted_proxies .iter() .map(ToString::to_string) .collect::>() .join(", "), }; Ok(settings_view( cx, lang, info, viewer.session.csrf_token.clone(), rows, file, notice_text(lang, &query.notice).map(str::to_owned), error_text(lang, &query.error).map(str::to_owned), )) } /// `POST /admin/settings`: saves the values that changed. Every value is checked first; if one is wrong, /// nothing is saved. The read of the saved values, the check and the write are one transaction, under the /// settings lock, so a save made by another request in between cannot be lost. #[route(POST "/admin/settings")] async fn save_settings(cx: &Cx, Form(form): Form) -> Result { let viewer = require_admin_csrf(cx, &form.csrf).await?; let state = app_context::(cx); let names = { let _guard = state.settings_lock.lock().await; let mut names: Vec<&'static str> = Vec::new(); let outcome = state .store .update_policy_settings(|saved| { let current = merge_saved_policy(&state.config.policy, saved); let mut next = current.clone(); let mut writes = Vec::new(); for (key, typed) in form.values() { let typed = typed.trim(); if typed == value_of(¤t, key) { continue; } next = next.set(key, typed)?; names.push(key); writes.push((format!("policy.{key}"), typed.to_owned())); } Ok(writes) }) .await; match outcome { Ok(()) => {} Err(im_core::Error::Invalid(_)) => return Ok(refused("/admin/settings", "settings")), Err(error) => return Err(error.into()), } if !names.is_empty() { // Refreshed from the committed rows, not from the values typed, so memory matches the database. let policy = effective_policy(&state.config, &state.store).await?; state.set_policy(policy); } names }; if names.is_empty() { return Ok(done("/admin/settings", "settings-saved")); } record( cx, Actor::User(&viewer.user.id), AuditAction::SettingsChanged, None, json!({ "keys": names }), ) .await; changed(&state.live); Ok(done("/admin/settings", "settings-saved")) } /// `POST /admin/settings/reset`: removes the saved value of one key, so the file value (or the default) /// applies again. #[route(POST "/admin/settings/reset")] async fn reset_setting(cx: &Cx, Form(form): Form) -> Result { let viewer = require_admin_csrf(cx, &form.csrf).await?; let Some(key) = POLICY_KEYS.iter().find(|key| **key == form.key) else { return Err(not_found().into()); }; let state = app_context::(cx); { let _guard = state.settings_lock.lock().await; state.store.delete_setting(&format!("policy.{key}")).await?; let policy = effective_policy(&state.config, &state.store).await?; state.set_policy(policy); } record( cx, Actor::User(&viewer.user.id), AuditAction::SettingsChanged, None, json!({ "reset": key }), ) .await; changed(&state.live); Ok(done("/admin/settings", "file-value")) } /// The file-only settings as text. struct FileValues { base_url: String, listen: String, database: String, data_dir: String, trusted_proxies: String, } /// The text of a source. fn source_text(lang: Lang, source: Source) -> &'static str { match source { Source::Ui => text(lang, A::SourceUi), Source::File => text(lang, A::SourceFile), Source::Default => text(lang, A::SourceDefault), } } /// The settings page: the editable table, the reset buttons, and the file-only values. #[allow(clippy::too_many_arguments)] fn settings_view( cx: &Cx, lang: Lang, info: ViewerInfo, csrf: String, rows: Vec, file: FileValues, success: Option, problem: Option, ) -> impl View { let resets: Vec<(&'static str, &'static str)> = rows .iter() .filter(|row| row.source == Source::Ui) .map(|row| (row.key, text(lang, labels(row.key).0))) .collect(); view! { cx => shell(title: text(lang, A::SettingsTitle), lang: lang, viewer: Some(info), tabs(lang: lang, current: Tab::Settings)

(text(lang, A::SettingsTitle))

(text(lang, A::SettingsIntro))

flash_messages(success: success, problem: problem)
for row in rows { setting_row(lang: lang, row: row) }
(text(lang, A::SettingName)) (text(lang, A::SettingValue)) (text(lang, A::SettingSource))
if !resets.is_empty() {

(text(lang, A::UseFileValue))

for (key, name) in resets { reset_form(lang: lang, csrf: csrf.clone(), key: key, name: name) } }

(text(lang, A::FileOnlyTitle))

(text(lang, A::FileOnlyIntro))

(text(lang, A::FileBaseUrl))
(file.base_url.clone())
(text(lang, A::FileListen))
(file.listen.clone())
(text(lang, A::FileDatabase))
(file.database.clone())
(text(lang, A::FileDataDir))
(file.data_dir.clone())
(text(lang, A::FileTrustedProxies))
(file.trusted_proxies.clone())
) } } /// One policy key: its label, its input with the value now, its hint, and its source. #[component] async fn setting_row(lang: Lang, row: SettingRow) -> Result { let (label, hint) = labels(row.key); let source = source_text(lang, row.source); Ok(view! {
(text(lang, hint))
(source) }) } /// A form that removes the saved value of one key. It sits outside the settings form, because forms do /// not nest. #[component] async fn reset_form( lang: Lang, csrf: String, key: &'static str, name: &'static str, ) -> Result { Ok(view! {
(name)
}) }