forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

settings.rs363 lines, 12.8 KiBHistoryRawDownload
1//! `/admin/settings`: the policy values that an administrator can change without a restart.
2//!
3//! Each value comes from one of three places, and the page shows which: a value saved here (`UI`), the
4//! configuration file (`file`), or the built-in default. A saved value is a `policy.<key>` setting; it wins
5//! over the file. Reset removes the saved value, so the file value applies again. Every value is checked
6//! with the same rules as the file before anything is written, so a bad form changes nothing.
7//!
8//! The file-only settings (base address, listen address, database, data directory, trusted proxies) are shown
9//! read-only: they are used when the server starts, so changing them here would do nothing until a restart.
10
11use im_core::config::{POLICY_KEYS, PolicyConfig};
12use im_core::model::AuditAction;
13use serde::Deserialize;
14use serde_json::json;
15use topcoat::Result;
16use topcoat::context::{Cx, app_context};
17use topcoat::router::content::Form;
18use topcoat::router::error::{SeeOther, not_found};
19use topcoat::router::{page, route};
20use topcoat::view::{View, component, view};
21
22use crate::audit::{Actor, record};
23use crate::auth::{require_admin, require_admin_csrf};
24use crate::boot::{effective_policy, merge_saved_policy};
25use crate::i18n::Lang;
26use crate::i18n::admin::{A, text};
27use crate::pages::admin::{
28 FlashQuery, Tab, changed, done, error_text, flash_messages, frame_info, notice_text, refused,
29 tabs,
30};
31use crate::state::AppState;
32use crate::views::{ViewerInfo, shell};
33
34/// The form of the settings: one text field per policy key, and the CSRF token.
35#[derive(Deserialize, Default)]
36struct SettingsForm {
37 #[serde(default)]
38 csrf: String,
39 #[serde(default)]
40 require_2fa_for_admins: String,
41 #[serde(default)]
42 max_sessions: String,
43 #[serde(default)]
44 session_max_days: String,
45 #[serde(default)]
46 invite_days: String,
47 #[serde(default)]
48 reset_minutes: String,
49 #[serde(default)]
50 email_change_hours: String,
51}
52
53impl SettingsForm {
54 /// Each key with the value typed for it, in the order of `POLICY_KEYS`.
55 fn values(&self) -> [(&'static str, &str); 6] {
56 [
57 ("require_2fa_for_admins", &self.require_2fa_for_admins),
58 ("max_sessions", &self.max_sessions),
59 ("session_max_days", &self.session_max_days),
60 ("invite_days", &self.invite_days),
61 ("reset_minutes", &self.reset_minutes),
62 ("email_change_hours", &self.email_change_hours),
63 ]
64 }
65}
66
67/// The form of a reset: the key to reset, and the CSRF token.
68#[derive(Deserialize, Default)]
69struct ResetForm {
70 #[serde(default)]
71 csrf: String,
72 #[serde(default)]
73 key: String,
74}
75
76/// The value of one policy key as text, the way the form shows and accepts it.
77fn value_of(policy: &PolicyConfig, key: &str) -> String {
78 match key {
79 "require_2fa_for_admins" => policy.require_2fa_for_admins.to_string(),
80 "max_sessions" => policy.max_sessions.to_string(),
81 "session_max_days" => policy.session_max_days.to_string(),
82 "invite_days" => policy.invite_days.to_string(),
83 "reset_minutes" => policy.reset_minutes.to_string(),
84 "email_change_hours" => policy.email_change_hours.to_string(),
85 _ => String::new(),
86 }
87}
88
89/// The labels and hints of a policy key.
90fn labels(key: &str) -> (A, A) {
91 match key {
92 "require_2fa_for_admins" => (A::SettingLabelRequire2fa, A::SettingHintRequire2fa),
93 "max_sessions" => (A::SettingLabelMaxSessions, A::SettingHintMaxSessions),
94 "session_max_days" => (A::SettingLabelSessionDays, A::SettingHintSessionDays),
95 "invite_days" => (A::SettingLabelInviteDays, A::SettingHintInviteDays),
96 "reset_minutes" => (A::SettingLabelResetMinutes, A::SettingHintResetMinutes),
97 _ => (A::SettingLabelEmailHours, A::SettingHintEmailHours),
98 }
99}
100
101/// One row of the settings table: the key, its value now, and where the value comes from.
102struct SettingRow {
103 key: &'static str,
104 value: String,
105 source: Source,
106}
107
108/// Where a policy value comes from.
109#[derive(Clone, Copy, PartialEq, Eq)]
110enum Source {
111 Ui,
112 File,
113 Default,
114}
115
116/// `GET /admin/settings`.
117#[page("/admin/settings")]
118async fn settings_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl View> {
119 let viewer = require_admin(cx).await?;
120 let state = app_context::<AppState>(cx);
121 let (lang, info) = frame_info(cx, &viewer);
122 let policy = state.policy();
123 let saved: Vec<String> = state
124 .store
125 .settings_with_prefix("policy.")
126 .await?
127 .into_iter()
128 .map(|(key, _)| key.trim_start_matches("policy.").to_owned())
129 .collect();
130 let rows: Vec<SettingRow> = POLICY_KEYS
131 .iter()
132 .map(|key| SettingRow {
133 key,
134 value: value_of(&policy, key),
135 source: if saved.iter().any(|name| name == key) {
136 Source::Ui
137 } else if state.config.explicit_policy.iter().any(|name| name == key) {
138 Source::File
139 } else {
140 Source::Default
141 },
142 })
143 .collect();
144 let file = FileValues {
145 base_url: state.config.base_url.clone(),
146 listen: state.config.listen.to_string(),
147 database: state.config.database.display().to_string(),
148 data_dir: state.config.data_dir.display().to_string(),
149 trusted_proxies: state
150 .config
151 .trusted_proxies
152 .iter()
153 .map(ToString::to_string)
154 .collect::<Vec<_>>()
155 .join(", "),
156 };
157 Ok(settings_view(
158 cx,
159 lang,
160 info,
161 viewer.session.csrf_token.clone(),
162 rows,
163 file,
164 notice_text(lang, &query.notice).map(str::to_owned),
165 error_text(lang, &query.error).map(str::to_owned),
166 ))
167}
168
169/// `POST /admin/settings`: saves the values that changed. Every value is checked first; if one is wrong,
170/// nothing is saved. The read of the saved values, the check and the write are one transaction, under the
171/// settings lock, so a save made by another request in between cannot be lost.
172#[route(POST "/admin/settings")]
173async fn save_settings(cx: &Cx, Form(form): Form<SettingsForm>) -> Result<SeeOther> {
174 let viewer = require_admin_csrf(cx, &form.csrf).await?;
175 let state = app_context::<AppState>(cx);
176 let names = {
177 let _guard = state.settings_lock.lock().await;
178 let mut names: Vec<&'static str> = Vec::new();
179 let outcome = state
180 .store
181 .update_policy_settings(|saved| {
182 let current = merge_saved_policy(&state.config.policy, saved);
183 let mut next = current.clone();
184 let mut writes = Vec::new();
185 for (key, typed) in form.values() {
186 let typed = typed.trim();
187 if typed == value_of(&current, key) {
188 continue;
189 }
190 next = next.set(key, typed)?;
191 names.push(key);
192 writes.push((format!("policy.{key}"), typed.to_owned()));
193 }
194 Ok(writes)
195 })
196 .await;
197 match outcome {
198 Ok(()) => {}
199 Err(im_core::Error::Invalid(_)) => return Ok(refused("/admin/settings", "settings")),
200 Err(error) => return Err(error.into()),
201 }
202 if !names.is_empty() {
203 // Refreshed from the committed rows, not from the values typed, so memory matches the database.
204 let policy = effective_policy(&state.config, &state.store).await?;
205 state.set_policy(policy);
206 }
207 names
208 };
209 if names.is_empty() {
210 return Ok(done("/admin/settings", "settings-saved"));
211 }
212 record(
213 cx,
214 Actor::User(&viewer.user.id),
215 AuditAction::SettingsChanged,
216 None,
217 json!({ "keys": names }),
218 )
219 .await;
220 changed(&state.live);
221 Ok(done("/admin/settings", "settings-saved"))
222}
223
224/// `POST /admin/settings/reset`: removes the saved value of one key, so the file value (or the default)
225/// applies again.
226#[route(POST "/admin/settings/reset")]
227async fn reset_setting(cx: &Cx, Form(form): Form<ResetForm>) -> Result<SeeOther> {
228 let viewer = require_admin_csrf(cx, &form.csrf).await?;
229 let Some(key) = POLICY_KEYS.iter().find(|key| **key == form.key) else {
230 return Err(not_found().into());
231 };
232 let state = app_context::<AppState>(cx);
233 {
234 let _guard = state.settings_lock.lock().await;
235 state.store.delete_setting(&format!("policy.{key}")).await?;
236 let policy = effective_policy(&state.config, &state.store).await?;
237 state.set_policy(policy);
238 }
239 record(
240 cx,
241 Actor::User(&viewer.user.id),
242 AuditAction::SettingsChanged,
243 None,
244 json!({ "reset": key }),
245 )
246 .await;
247 changed(&state.live);
248 Ok(done("/admin/settings", "file-value"))
249}
250
251/// The file-only settings as text.
252struct FileValues {
253 base_url: String,
254 listen: String,
255 database: String,
256 data_dir: String,
257 trusted_proxies: String,
258}
259
260/// The text of a source.
261fn source_text(lang: Lang, source: Source) -> &'static str {
262 match source {
263 Source::Ui => text(lang, A::SourceUi),
264 Source::File => text(lang, A::SourceFile),
265 Source::Default => text(lang, A::SourceDefault),
266 }
267}
268
269/// The settings page: the editable table, the reset buttons, and the file-only values.
270#[allow(clippy::too_many_arguments)]
271fn settings_view(
272 cx: &Cx,
273 lang: Lang,
274 info: ViewerInfo,
275 csrf: String,
276 rows: Vec<SettingRow>,
277 file: FileValues,
278 success: Option<String>,
279 problem: Option<String>,
280) -> impl View {
281 let resets: Vec<(&'static str, &'static str)> = rows
282 .iter()
283 .filter(|row| row.source == Source::Ui)
284 .map(|row| (row.key, text(lang, labels(row.key).0)))
285 .collect();
286 view! { cx =>
287 shell(title: text(lang, A::SettingsTitle), lang: lang, viewer: Some(info),
288 tabs(lang: lang, current: Tab::Settings)
289 <section class="stack">
290 <h1>(text(lang, A::SettingsTitle))</h1>
291 <p class="muted">(text(lang, A::SettingsIntro))</p>
292 flash_messages(success: success, problem: problem)
293 <form method="post" action="/admin/settings" class="stack">
294 <input type="hidden" name="csrf" value=(csrf.clone())>
295 <table class="settings">
296 <thead><tr>
297 <th>(text(lang, A::SettingName))</th>
298 <th>(text(lang, A::SettingValue))</th>
299 <th>(text(lang, A::SettingSource))</th>
300 </tr></thead>
301 <tbody>
302 for row in rows {
303 setting_row(lang: lang, row: row)
304 }
305 </tbody>
306 </table>
307 <button type="submit" class="button primary">(text(lang, A::Save))</button>
308 </form>
309 if !resets.is_empty() {
310 <h2>(text(lang, A::UseFileValue))</h2>
311 for (key, name) in resets {
312 reset_form(lang: lang, csrf: csrf.clone(), key: key, name: name)
313 }
314 }
315 <h2>(text(lang, A::FileOnlyTitle))</h2>
316 <p class="muted">(text(lang, A::FileOnlyIntro))</p>
317 <dl class="facts">
318 <dt>(text(lang, A::FileBaseUrl))</dt><dd>(file.base_url.clone())</dd>
319 <dt>(text(lang, A::FileListen))</dt><dd>(file.listen.clone())</dd>
320 <dt>(text(lang, A::FileDatabase))</dt><dd>(file.database.clone())</dd>
321 <dt>(text(lang, A::FileDataDir))</dt><dd>(file.data_dir.clone())</dd>
322 <dt>(text(lang, A::FileTrustedProxies))</dt><dd>(file.trusted_proxies.clone())</dd>
323 </dl>
324 </section>
325 )
326 }
327}
328
329/// One policy key: its label, its input with the value now, its hint, and its source.
330#[component]
331async fn setting_row(lang: Lang, row: SettingRow) -> Result<impl View> {
332 let (label, hint) = labels(row.key);
333 let source = source_text(lang, row.source);
334 Ok(view! {
335 <tr>
336 <td>
337 <label for=(row.key)>(text(lang, label))</label>
338 <div class="hint">(text(lang, hint))</div>
339 </td>
340 <td><input id=(row.key) name=(row.key) type="text" autocomplete="off" value=(row.value.clone())></td>
341 <td class="muted">(source)</td>
342 </tr>
343 })
344}
345
346/// A form that removes the saved value of one key. It sits outside the settings form, because forms do
347/// not nest.
348#[component]
349async fn reset_form(
350 lang: Lang,
351 csrf: String,
352 key: &'static str,
353 name: &'static str,
354) -> Result<impl View> {
355 Ok(view! {
356 <form method="post" action="/admin/settings/reset" class="inline-form">
357 <input type="hidden" name="csrf" value=(csrf)>
358 <input type="hidden" name="key" value=(key)>
359 <span class="muted">(name)</span>
360 <button type="submit" class="button ghost">(text(lang, A::UseFileValue))</button>
361 </form>
362 })
363}