forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

admin.rs1077 lines, 37.6 KiBHistoryRawDownload
1//! The administration page (`GET /admin`) and its writes. Only an instance administrator (the `im_admin`
2//! claim, stored as `members.is_admin`) sees it. Anyone else gets `404`, and so does a write from them.
3//!
4//! The page shows: health (the database and the blob store answer), the storage backend and its free space
5//! or reachability, the backup schedule with the last success and attempt, an alert for a failed latest run,
6//! a warning when no success is recent, and a button that asks for a backup now, the base URL, every person
7//! with their quota, every service with its usage and quota, the defaults with the layer each value comes from
8//! (UI, file or built-in default), and the audit log with keyset paging and filters.
9//!
10//! Every write is checked (administrator, then CSRF, both before any side effect), validated, and then
11//! audited after it commits. The audit writer never fails a request. The defaults form is all-or-nothing: if
12//! one value is out of range, nothing is written. A backup request only wakes the backup worker: the run itself
13//! happens in the background, and a request made while one is pending or running starts nothing.
14
15use std::time::Duration;
16
17use in_core::config::Backend;
18use in_core::error::Error as CoreError;
19use in_core::settings::{
20 self, DEFAULT_QUOTA_KEY, DEFAULT_SERVICE_QUOTA_KEY, FIELDS, LINK_MAX_DAYS_KEY, MAX_UPLOAD_KEY,
21 Mode, PURGE_KEY, Source,
22};
23use in_core::store::audit::{AuditQuery, AuditRow};
24use in_core::store::members::Member;
25use in_core::store::objects::Service;
26use in_core::store::{Store, objects::Usage};
27use serde::Deserialize;
28use serde_json::json;
29use topcoat::Result;
30use topcoat::context::{Cx, app_context};
31use topcoat::router::content::Form;
32use topcoat::router::error::{SeeOther, not_found, see_other};
33use topcoat::router::response::Response;
34use topcoat::router::{page, parse_query_params, path_param_segment, route};
35use topcoat::view::{View, component, view};
36
37use crate::audit::{self, Entry};
38use crate::auth::{Viewer, require_admin, require_admin_csrf};
39use crate::backup::{LAST_ATTEMPT_AT, LAST_ERROR, LAST_SUCCESS_AT, is_stale};
40use crate::health::{probe_blobs, probe_database};
41use crate::i18n::Lang;
42use crate::i18n::admin::{AK, a, backup_failed, backup_schedule, notice, refusal};
43use crate::live::{Topic, stream_changes};
44use crate::oidc::percent_encode;
45use crate::pages::drive::{viewer_lang, with_param};
46use crate::state::AppState;
47use crate::views::drive::{size_text, stamp_text};
48use crate::views::{ViewerInfo, alert, notice as flash_notice, shell, warning};
49
50/// One mebibyte, the unit of the admin's byte fields.
51const MIB: i64 = 1024 * 1024;
52
53/// Audit rows per page.
54pub const AUDIT_PAGE: usize = 50;
55
56/// How long a probe of the blob store may take on this page. A slow bucket shows as not reachable.
57const PROBE_WAIT: Duration = Duration::from_secs(2);
58
59/// The query of the page: notice and refusal words, the audit filters and the keyset cursor.
60#[derive(Debug, Default, Deserialize)]
61#[serde(default)]
62pub struct AdminQuery {
63 /// A word from a successful write.
64 pub notice: String,
65 /// A word from a refused write.
66 pub refusal: String,
67 /// Exact action filter.
68 pub action: String,
69 /// Exact actor id filter.
70 pub actor: String,
71 /// Exact target kind filter.
72 pub target: String,
73 /// Cursor `at|id` of the last row of the previous page.
74 pub before: String,
75}
76
77/// The form of a quota write: the CSRF token and the quota in MiB.
78#[derive(Debug, Default, Deserialize)]
79#[serde(default)]
80pub struct QuotaForm {
81 /// The CSRF token of the session.
82 pub csrf: String,
83 /// The new quota, in MiB.
84 pub quota_mib: String,
85}
86
87/// The form of the defaults. Every field is optional on the wire; blank clears the UI override.
88#[derive(Debug, Default, Deserialize)]
89#[serde(default)]
90pub struct DefaultsForm {
91 /// The CSRF token of the session.
92 pub csrf: String,
93 /// New person's quota, MiB.
94 pub default_quota_mib: String,
95 /// New service's quota, MiB.
96 pub default_service_quota_mib: String,
97 /// Days before a purge.
98 pub purge_after_days: String,
99 /// Largest upload, MiB.
100 pub max_upload_mib: String,
101 /// Longest share link, days.
102 pub link_max_days: String,
103}
104
105/// One row of the defaults table.
106#[derive(Debug, Clone)]
107pub struct DefaultRow {
108 /// Form field name.
109 pub field: &'static str,
110 /// Heading of the row.
111 pub label: AK,
112 /// The UI override in the form's unit, blank when none is set.
113 pub input: String,
114 /// The effective value, formatted.
115 pub shown: String,
116 /// Where the effective value comes from.
117 pub source: Source,
118 /// How the value may change.
119 pub mode: Mode,
120}
121
122/// What the page shows about the storage backend.
123#[derive(Debug, Clone)]
124pub struct StorageStatus {
125 /// `local` or `s3`.
126 pub backend: &'static str,
127 /// The local blob path, or the bucket name.
128 pub location: String,
129 /// Free bytes on the local path, when it could be read.
130 pub free: Option<i64>,
131 /// Whether the S3 bucket answered a probe.
132 pub reachable: Option<bool>,
133 /// The base URL from the file.
134 pub base_url: String,
135}
136
137/// The health probes: whether each part answered.
138#[derive(Debug, Clone, Copy)]
139pub struct Probes {
140 /// The database answered a `SELECT 1`.
141 pub database: bool,
142 /// The blob store answered.
143 pub blobs: bool,
144}
145
146/// The form of the backup button: only the CSRF token of the session.
147#[derive(Debug, Default, Deserialize)]
148#[serde(default)]
149pub struct BackupForm {
150 /// The CSRF token of the session.
151 pub csrf: String,
152}
153
154/// What the backups section shows: where the sets go, how often a run happens, and the outcome the worker
155/// recorded. `None` when the configuration has no `[backup]` table.
156#[derive(Debug, Clone)]
157pub struct BackupStatus {
158 /// The directory that receives the sets.
159 pub dir: String,
160 /// Hours between scheduled runs.
161 pub interval_hours: u32,
162 /// Sets kept.
163 pub keep: u32,
164 /// When a run was last attempted, if one ran.
165 pub last_attempt: Option<String>,
166 /// When a run last succeeded, if one did.
167 pub last_success: Option<String>,
168 /// The short error of the latest run, present only while that run failed.
169 pub last_error: Option<String>,
170 /// True when no success is recent enough (see `backup::is_stale`).
171 pub stale: bool,
172}
173
174/// The backups section's data: the configuration and what the worker recorded. `None` when backups are off.
175async fn backup_status(state: &AppState) -> Result<Option<BackupStatus>> {
176 let Some(config) = state.config.backup.as_ref() else {
177 return Ok(None);
178 };
179 let last_success = state.store.get_setting(LAST_SUCCESS_AT).await?;
180 Ok(Some(BackupStatus {
181 dir: config.dir.display().to_string(),
182 interval_hours: config.interval_hours,
183 keep: config.keep,
184 last_attempt: state.store.get_setting(LAST_ATTEMPT_AT).await?,
185 stale: is_stale(last_success.as_deref(), config.interval_hours),
186 last_success,
187 last_error: state
188 .store
189 .get_setting(LAST_ERROR)
190 .await?
191 .filter(|error| !error.is_empty()),
192 }))
193}
194
195/// Whether a field's form unit is MiB.
196fn is_mib(key: &str) -> bool {
197 key == DEFAULT_QUOTA_KEY || key == DEFAULT_SERVICE_QUOTA_KEY || key == MAX_UPLOAD_KEY
198}
199
200/// The form field name of a runtime setting.
201fn field_name(key: &str) -> &'static str {
202 match key {
203 DEFAULT_QUOTA_KEY => "default_quota_mib",
204 DEFAULT_SERVICE_QUOTA_KEY => "default_service_quota_mib",
205 PURGE_KEY => "purge_after_days",
206 MAX_UPLOAD_KEY => "max_upload_mib",
207 _ => "link_max_days",
208 }
209}
210
211/// The label heading of a runtime setting.
212fn label_of(key: &str) -> AK {
213 match key {
214 DEFAULT_QUOTA_KEY => AK::DefaultQuotaLabel,
215 DEFAULT_SERVICE_QUOTA_KEY => AK::DefaultServiceQuotaLabel,
216 PURGE_KEY => AK::PurgeLabel,
217 MAX_UPLOAD_KEY => AK::MaxUploadLabel,
218 _ => AK::LinkMaxLabel,
219 }
220}
221
222/// Converts a MiB figure from a form to bytes. Blank is "no value" and is passed through as blank.
223fn mib_to_text(text: &str) -> std::result::Result<String, CoreError> {
224 let text = text.trim();
225 if text.is_empty() {
226 return Ok(String::new());
227 }
228 text.parse::<i64>()
229 .ok()
230 .and_then(|mib| mib.checked_mul(MIB))
231 .map(|bytes| bytes.to_string())
232 .ok_or_else(|| CoreError::Invalid("quota_range".into()))
233}
234
235/// The bytes of a person's or a service's quota from its form: required, and within the field's bounds.
236fn quota_bytes(text: &str) -> std::result::Result<i64, CoreError> {
237 let text = mib_to_text(text)?;
238 let field = settings::field(DEFAULT_QUOTA_KEY)
239 .ok_or_else(|| CoreError::Invalid("quota_range".into()))?;
240 let bytes: i64 = text
241 .parse()
242 .map_err(|_| CoreError::Invalid("quota_range".into()))?;
243 settings::check(field, bytes).map_err(|_| CoreError::Invalid("quota_range".into()))
244}
245
246/// Maps a refused write to the answer: a missing item is `404`, a refusal goes back to the page with its
247/// word, anything else is a server error.
248fn refuse(error: CoreError) -> Result<SeeOther> {
249 match error {
250 CoreError::NotFound => Err(not_found().into()),
251 CoreError::Invalid(word) | CoreError::Conflict(word) | CoreError::Forbidden(word) => {
252 let safe = if word.chars().all(|c| c.is_ascii_lowercase() || c == '_') {
253 word
254 } else {
255 "generic".to_owned()
256 };
257 Ok(see_other(with_param("/admin", "refusal", &safe)))
258 }
259 other => Err(other.into()),
260 }
261}
262
263/// Appends one audit entry for a change made by `actor`.
264async fn audited(
265 state: &AppState,
266 actor: &Viewer,
267 action: &str,
268 target_kind: &str,
269 target_id: &str,
270 data: serde_json::Value,
271) {
272 audit::record(
273 state,
274 Entry {
275 actor: Some(&actor.member.sub),
276 action,
277 target_kind,
278 target_id: Some(target_id),
279 data,
280 },
281 )
282 .await;
283}
284
285/// The rows of the defaults table: each field's effective value, its source and its mode.
286async fn default_rows(state: &AppState) -> Result<Vec<DefaultRow>> {
287 let mut rows = Vec::with_capacity(FIELDS.len());
288 for field in &FIELDS {
289 let resolved = settings::resolve(&state.store, &state.config.limits, field.key).await?;
290 let ui = state
291 .store
292 .get_setting(field.key)
293 .await?
294 .and_then(|text| text.trim().parse::<i64>().ok());
295 let mib = is_mib(field.key);
296 let input = match ui {
297 Some(value) if mib => (value / MIB).to_string(),
298 Some(value) => value.to_string(),
299 None => String::new(),
300 };
301 let shown = if mib {
302 size_text(resolved.value)
303 } else {
304 resolved.value.to_string()
305 };
306 rows.push(DefaultRow {
307 field: field_name(field.key),
308 label: label_of(field.key),
309 input,
310 shown,
311 source: resolved.source,
312 mode: field.mode,
313 });
314 }
315 Ok(rows)
316}
317
318/// What the storage section needs: the backend, its location and its free space or reachability.
319async fn storage_status(state: &AppState) -> StorageStatus {
320 let base_url = state.config.base_url.clone();
321 match state.config.storage.backend {
322 Backend::Local => {
323 let path = state.config.data_dir.join(crate::boot::BLOB_DIR);
324 StorageStatus {
325 backend: "local",
326 location: path.display().to_string(),
327 free: free_space(&path),
328 reachable: None,
329 base_url,
330 }
331 }
332 Backend::S3 => {
333 let reachable = tokio::time::timeout(PROBE_WAIT, probe_blobs(state.blobs.as_ref()))
334 .await
335 .is_ok_and(|outcome| outcome.is_ok());
336 StorageStatus {
337 backend: "s3",
338 location: state
339 .config
340 .storage
341 .s3
342 .as_ref()
343 .map(|s3| s3.bucket.clone())
344 .unwrap_or_default(),
345 free: None,
346 reachable: Some(reachable),
347 base_url,
348 }
349 }
350 }
351}
352
353/// Free bytes available to this user on the filesystem of `path`, when it can be read.
354fn free_space(path: &std::path::Path) -> Option<i64> {
355 let stat = rustix::fs::statvfs(path).ok()?;
356 let bytes = u128::from(stat.f_bavail) * u128::from(stat.f_frsize);
357 Some(i64::try_from(bytes).unwrap_or(i64::MAX))
358}
359
360/// Both health probes, each within the probe deadline.
361async fn probe_all(state: &AppState) -> Probes {
362 let (database, blobs) = tokio::join!(
363 tokio::time::timeout(PROBE_WAIT, probe_database(state)),
364 tokio::time::timeout(PROBE_WAIT, probe_blobs(state.blobs.as_ref())),
365 );
366 Probes {
367 database: database.is_ok_and(|r| r.is_ok()),
368 blobs: blobs.is_ok_and(|r| r.is_ok()),
369 }
370}
371
372/// Parses the `at|id` cursor. Anything malformed starts the log from the top.
373fn parse_cursor(raw: &str) -> Option<(String, String)> {
374 let (at, id) = raw.split_once('|')?;
375 (!at.is_empty() && !id.is_empty()).then(|| (at.to_owned(), id.to_owned()))
376}
377
378/// The link to the next page of the log, keeping the filters.
379fn older_link(query: &AdminQuery, last: &AuditRow) -> String {
380 format!(
381 "/admin?action={}&actor={}&target={}&before={}",
382 percent_encode(&query.action),
383 percent_encode(&query.actor),
384 percent_encode(&query.target),
385 percent_encode(&format!("{}|{}", last.at, last.id)),
386 )
387}
388
389/// The health line of one probe.
390#[component]
391async fn probe_line(lang: Lang, label: &str, ok: bool) -> Result<impl View> {
392 let word = if ok {
393 a(lang, AK::HealthOk)
394 } else {
395 a(lang, AK::HealthFail)
396 };
397 Ok(view! { <li>(label) ": " <strong>(word)</strong></li> })
398}
399
400/// The health section.
401#[component]
402async fn health_section(lang: Lang, probes: Probes, build_sha: &str) -> Result<impl View> {
403 Ok(view! {
404 <section class="admin-section">
405 <h2>(a(lang, AK::Health))</h2>
406 <ul>
407 probe_line(lang: lang, label: a(lang, AK::Database), ok: probes.database)
408 probe_line(lang: lang, label: a(lang, AK::Blobs), ok: probes.blobs)
409 <li>(a(lang, AK::Build)) ": " <code>(build_sha)</code></li>
410 </ul>
411 </section>
412 })
413}
414
415/// The storage and base URL section.
416#[component]
417async fn storage_section(lang: Lang, status: &StorageStatus) -> Result<impl View> {
418 let free = status
419 .free
420 .map_or_else(|| a(lang, AK::NotAvailable).to_owned(), size_text);
421 let reach = match status.reachable {
422 Some(true) => a(lang, AK::Reachable),
423 Some(false) => a(lang, AK::Unreachable),
424 None => a(lang, AK::NotAvailable),
425 };
426 Ok(view! {
427 <section class="admin-section">
428 <h2>(a(lang, AK::Storage))</h2>
429 <ul>
430 <li>(a(lang, AK::Backend)) ": " (status.backend)</li>
431 <li>(a(lang, AK::LocalPath)) ": " <code>(status.location.as_str())</code></li>
432 if status.backend == "local" {
433 <li>(a(lang, AK::FreeSpace)) ": " (free.as_str())</li>
434 } else {
435 <li>(reach)</li>
436 }
437 </ul>
438 <h3>(a(lang, AK::BaseUrl))</h3>
439 <p><code>(status.base_url.as_str())</code> " " <span class="muted">(a(lang, AK::BaseUrlFile))</span></p>
440 </section>
441 })
442}
443
444/// The backups section: the directory and schedule, the last success and attempt, an alert when the latest
445/// run failed, a warning when no success is recent, and the button that asks for a run now. Without
446/// `[backup]` it says that backups are off.
447#[component]
448async fn backup_section(
449 lang: Lang,
450 status: Option<&BackupStatus>,
451 csrf: &str,
452) -> Result<impl View> {
453 let schedule = status.map_or_else(String::new, |s| {
454 backup_schedule(lang, s.interval_hours, s.keep)
455 });
456 let dir = status.map_or_else(String::new, |s| s.dir.clone());
457 let never = || a(lang, AK::BackupNever).to_owned();
458 let last_success = status.and_then(|s| s.last_success.as_deref());
459 let last_success = last_success.map_or_else(never, stamp_text);
460 let last_attempt = status.and_then(|s| s.last_attempt.as_deref());
461 let last_attempt = last_attempt.map_or_else(never, stamp_text);
462 let failed = status
463 .and_then(|s| s.last_error.as_deref())
464 .map(|error| backup_failed(lang, error));
465 let stale = status.is_some_and(|s| s.stale);
466 Ok(view! {
467 <section class="admin-section">
468 <h2>(a(lang, AK::Backups))</h2>
469 if status.is_some() {
470 <ul>
471 <li>(a(lang, AK::BackupDir)) ": " <code>(dir.as_str())</code></li>
472 <li>(schedule.as_str())</li>
473 <li>(a(lang, AK::BackupLast)) ": " (last_success.as_str())</li>
474 <li>(a(lang, AK::BackupAttempt)) ": " (last_attempt.as_str())</li>
475 </ul>
476 if let Some(text) = failed.as_deref() {
477 alert(message: text)
478 }
479 if stale {
480 warning(message: a(lang, AK::BackupStale))
481 }
482 <form method="post" action="/admin/backup" class="inline-form">
483 <input type="hidden" name="csrf" value=(csrf)>
484 <button class="button" type="submit">(a(lang, AK::BackupNow))</button>
485 </form>
486 } else {
487 <p class="muted">(a(lang, AK::BackupOff))</p>
488 }
489 </section>
490 })
491}
492
493/// One person in the people table, with the form that sets their quota.
494#[component]
495async fn person_row(lang: Lang, member: &Member, csrf: &str) -> Result<impl View> {
496 let action = format!("/admin/people/{}/quota", member.sub);
497 let quota_mib = (member.quota_bytes / MIB).to_string();
498 let used = size_text(member.used_bytes);
499 let quota = size_text(member.quota_bytes);
500 let input_id = format!("q-{}", member.sub);
501 Ok(view! {
502 <tr>
503 <td>(member.name.as_str())
504 if member.is_admin {
505 " " <span class="badge accent">(a(lang, AK::AdminBadge))</span>
506 }
507 if member.disabled {
508 " " <span class="badge">(a(lang, AK::DisabledBadge))</span>
509 }
510 </td>
511 <td>(member.email.as_str())</td>
512 <td>(used.as_str()) " / " (quota.as_str())</td>
513 <td>
514 <form method="post" action=(action.as_str()) class="inline-form">
515 <input type="hidden" name="csrf" value=(csrf)>
516 <label class="sr-only" for=(input_id.as_str())>(a(lang, AK::QuotaMib))</label>
517 <input id=(input_id.as_str()) name="quota_mib" inputmode="numeric" value=(quota_mib.as_str()) size="8">
518 <button class="button" type="submit">(a(lang, AK::SaveQuota))</button>
519 </form>
520 </td>
521 </tr>
522 })
523}
524
525/// The people section.
526#[component]
527async fn people_section(lang: Lang, members: &[Member], csrf: &str) -> Result<impl View> {
528 Ok(view! {
529 <section class="admin-section">
530 <h2>(a(lang, AK::People))</h2>
531 <table class="table">
532 <thead><tr>
533 <th>(a(lang, AK::ColName))</th>
534 <th>(a(lang, AK::ColEmail))</th>
535 <th>(a(lang, AK::ColUsed)) " / " (a(lang, AK::ColQuota))</th>
536 <th>(a(lang, AK::ColSetQuota))</th>
537 </tr></thead>
538 <tbody>
539 for member in members {
540 person_row(lang: lang, member: member, csrf: csrf)
541 }
542 </tbody>
543 </table>
544 </section>
545 })
546}
547
548/// One service in the services table, with the form that sets its quota.
549#[component]
550async fn service_row(
551 lang: Lang,
552 service: &Service,
553 usage: &Usage,
554 csrf: &str,
555) -> Result<impl View> {
556 let action = format!("/admin/services/{}/quota", service.key);
557 let quota_mib = (usage.quota_bytes / MIB).to_string();
558 let used = size_text(usage.used_bytes);
559 let quota = size_text(usage.quota_bytes);
560 let objects = usage.objects.to_string();
561 let input_id = format!("s-{}", service.key);
562 Ok(view! {
563 <tr>
564 <td>(service.key.as_str())</td>
565 <td>(objects.as_str())</td>
566 <td>(used.as_str()) " / " (quota.as_str())</td>
567 <td>
568 <form method="post" action=(action.as_str()) class="inline-form">
569 <input type="hidden" name="csrf" value=(csrf)>
570 <label class="sr-only" for=(input_id.as_str())>(a(lang, AK::QuotaMib))</label>
571 <input id=(input_id.as_str()) name="quota_mib" inputmode="numeric" value=(quota_mib.as_str()) size="8">
572 <button class="button" type="submit">(a(lang, AK::SaveQuota))</button>
573 </form>
574 </td>
575 </tr>
576 })
577}
578
579/// The services section. Each row carries its usage, read by the caller.
580#[component]
581async fn services_section(lang: Lang, rows: &[(Service, Usage)], csrf: &str) -> Result<impl View> {
582 Ok(view! {
583 <section class="admin-section">
584 <h2>(a(lang, AK::Services))</h2>
585 if rows.is_empty() {
586 <p class="muted">(a(lang, AK::ServicesEmpty))</p>
587 } else {
588 <table class="table">
589 <thead><tr>
590 <th>"key"</th>
591 <th>(a(lang, AK::ColObjects))</th>
592 <th>(a(lang, AK::ColUsed)) " / " (a(lang, AK::ColQuota))</th>
593 <th>(a(lang, AK::ColSetQuota))</th>
594 </tr></thead>
595 <tbody>
596 for (service, usage) in rows {
597 service_row(lang: lang, service: service, usage: usage, csrf: csrf)
598 }
599 </tbody>
600 </table>
601 }
602 </section>
603 })
604}
605
606/// One row of the defaults table: the field, the value in effect, its source, its mode and the input.
607#[component]
608async fn default_field(lang: Lang, row: &DefaultRow) -> Result<impl View> {
609 let source = match row.source {
610 Source::Ui => a(lang, AK::SourceUi),
611 Source::File => a(lang, AK::SourceFile),
612 Source::Default => a(lang, AK::SourceDefault),
613 };
614 let mode = match row.mode {
615 Mode::Live => a(lang, AK::ModeLive),
616 Mode::Restart => a(lang, AK::ModeRestart),
617 Mode::ReadOnly => a(lang, AK::ModeReadOnly),
618 };
619 let input_id = format!("d-{}", row.field);
620 Ok(view! {
621 <tr>
622 <td><label for=(input_id.as_str())>(a(lang, row.label))</label></td>
623 <td><input id=(input_id.as_str()) name=(row.field) inputmode="numeric" value=(row.input.as_str()) size="10"></td>
624 <td>(row.shown.as_str())</td>
625 <td>(source)</td>
626 <td>(mode)</td>
627 </tr>
628 })
629}
630
631/// The defaults section: the form of the five defaults.
632#[component]
633async fn defaults_section(lang: Lang, rows: &[DefaultRow], csrf: &str) -> Result<impl View> {
634 Ok(view! {
635 <section class="admin-section">
636 <h2>(a(lang, AK::Defaults))</h2>
637 <p class="muted">(a(lang, AK::DefaultsHint))</p>
638 <form method="post" action="/admin/defaults">
639 <input type="hidden" name="csrf" value=(csrf)>
640 <table class="table">
641 <thead><tr>
642 <th>(a(lang, AK::ColName))</th>
643 <th>(a(lang, AK::ColValue))</th>
644 <th>"="</th>
645 <th>(a(lang, AK::ColSource))</th>
646 <th>(a(lang, AK::ColMode))</th>
647 </tr></thead>
648 <tbody>
649 for row in rows {
650 default_field(lang: lang, row: row)
651 }
652 </tbody>
653 </table>
654 <button class="button" type="submit">(a(lang, AK::SaveDefaults))</button>
655 </form>
656 </section>
657 })
658}
659
660/// One audit row: when, who, what, to what, and the details.
661#[component]
662async fn audit_row(row: &AuditRow) -> Result<impl View> {
663 let when = stamp_text(&row.at);
664 let actor = match &row.actor_id {
665 Some(id) => format!("{} {id}", row.actor_kind),
666 None => row.actor_kind.clone(),
667 };
668 let target = match &row.target_id {
669 Some(id) => format!("{} {id}", row.target_kind),
670 None => row.target_kind.clone(),
671 };
672 Ok(view! {
673 <tr>
674 <td>(when.as_str())</td>
675 <td>(actor.as_str())</td>
676 <td><code>(row.action.as_str())</code></td>
677 <td>(target.as_str())</td>
678 <td><code>(row.data.as_str())</code></td>
679 </tr>
680 })
681}
682
683/// The audit section: the filters, the page of rows and the link to the next page.
684#[component]
685async fn audit_section(
686 lang: Lang,
687 rows: &[AuditRow],
688 action: &str,
689 actor: &str,
690 target: &str,
691 older: Option<&str>,
692) -> Result<impl View> {
693 Ok(view! {
694 <section class="admin-section" data-live="/live/admin">
695 <h2>(a(lang, AK::Audit))</h2>
696 <form method="get" action="/admin" class="inline-form">
697 <label for="f-action">(a(lang, AK::FilterAction))</label>
698 <input id="f-action" name="action" value=(action) size="18">
699 <label for="f-actor">(a(lang, AK::FilterActor))</label>
700 <input id="f-actor" name="actor" value=(actor) size="18">
701 <label for="f-target">(a(lang, AK::FilterTarget))</label>
702 <input id="f-target" name="target" value=(target) size="12">
703 <button class="button" type="submit">(a(lang, AK::Filter))</button>
704 </form>
705 if rows.is_empty() {
706 <p class="muted">(a(lang, AK::AuditEmpty))</p>
707 } else {
708 <table class="table">
709 <thead><tr>
710 <th>(a(lang, AK::ColAt))</th>
711 <th>(a(lang, AK::ColActor))</th>
712 <th>(a(lang, AK::ColAction))</th>
713 <th>(a(lang, AK::ColTarget))</th>
714 <th>(a(lang, AK::ColDetails))</th>
715 </tr></thead>
716 <tbody>
717 for row in rows {
718 audit_row(row: row)
719 }
720 </tbody>
721 </table>
722 }
723 if let Some(link) = older {
724 <p><a href=(link)>(a(lang, AK::OlderEntries))</a></p>
725 }
726 </section>
727 })
728}
729
730/// The whole page body: the notice or refusal, then the sections.
731#[allow(clippy::too_many_arguments)] // The page has this many separate parts; a struct would only hide them.
732#[component]
733async fn admin_body(
734 lang: Lang,
735 csrf: &str,
736 flash: Option<&str>,
737 refusal_text: Option<&str>,
738 probes: Probes,
739 build_sha: &str,
740 storage: &StorageStatus,
741 backups: Option<&BackupStatus>,
742 members: &[Member],
743 services: &[(Service, Usage)],
744 defaults: &[DefaultRow],
745 audit_rows: &[AuditRow],
746 filters: (&str, &str, &str),
747 older: Option<&str>,
748) -> Result<impl View> {
749 Ok(view! {
750 <section class="admin">
751 <h1>(a(lang, AK::Title))</h1>
752 <p class="muted">(a(lang, AK::Hint))</p>
753 if let Some(text) = flash {
754 flash_notice(message: text)
755 }
756 if let Some(text) = refusal_text {
757 alert(message: text)
758 }
759 health_section(lang: lang, probes: probes, build_sha: build_sha)
760 storage_section(lang: lang, status: storage)
761 backup_section(lang: lang, status: backups, csrf: csrf)
762 people_section(lang: lang, members: members, csrf: csrf)
763 services_section(lang: lang, rows: services, csrf: csrf)
764 defaults_section(lang: lang, rows: defaults, csrf: csrf)
765 audit_section(lang: lang, rows: audit_rows, action: filters.0, actor: filters.1, target: filters.2, older: older)
766 </section>
767 })
768}
769
770/// `GET /admin`.
771#[page("/admin")]
772async fn admin_page(cx: &Cx) -> Result<impl View> {
773 let state = app_context::<AppState>(cx);
774 let viewer = require_admin(cx).await?;
775 let lang = viewer_lang(cx, &viewer);
776 let query: AdminQuery = parse_query_params(cx).unwrap_or_default();
777
778 let members = state.store.list_members().await?;
779 let mut services = Vec::new();
780 for service in state.store.services().await? {
781 let usage = state.store.service_usage(&service.key).await?;
782 services.push((service, usage));
783 }
784 let defaults = default_rows(state).await?;
785 let storage = storage_status(state).await;
786 let backups = backup_status(state).await?;
787 let probes = probe_all(state).await;
788 let page = state
789 .store
790 .audit_page(&AuditQuery {
791 action: query.action.trim().to_owned(),
792 actor_id: query.actor.trim().to_owned(),
793 target_kind: query.target.trim().to_owned(),
794 before: parse_cursor(&query.before),
795 limit: AUDIT_PAGE + 1,
796 })
797 .await?;
798 let has_more = page.len() > AUDIT_PAGE;
799 let shown: Vec<AuditRow> = page.into_iter().take(AUDIT_PAGE).collect();
800 let older = if has_more {
801 shown.last().map(|last| older_link(&query, last))
802 } else {
803 None
804 };
805
806 let flash = (!query.notice.is_empty())
807 .then(|| notice(lang, &query.notice))
808 .flatten();
809 let refusal_text = (!query.refusal.is_empty()).then(|| refusal(lang, &query.refusal));
810 let info = ViewerInfo::of(&viewer, state.family.list());
811 let build = env!("IN_BUILD_SHA");
812 Ok(view! {
813 shell(title: a(lang, AK::Title), lang: lang, viewer: Some(&info),
814 admin_body(
815 lang: lang,
816 csrf: viewer.session.csrf_token.as_str(),
817 flash: flash,
818 refusal_text: refusal_text,
819 probes: probes,
820 build_sha: build,
821 storage: &storage,
822 backups: backups.as_ref(),
823 members: &members,
824 services: &services,
825 defaults: &defaults,
826 audit_rows: &shown,
827 filters: (query.action.trim(), query.actor.trim(), query.target.trim()),
828 older: older.as_deref(),
829 )
830 )
831 })
832}
833
834/// `POST /admin/people/{sub}/quota`: sets a person's quota. The administrator and the CSRF token are checked
835/// first; the change is audited after it commits.
836#[route(POST "/admin/people/{sub}/quota")]
837async fn set_person_quota(cx: &Cx, Form(form): Form<QuotaForm>) -> Result<SeeOther> {
838 let state = app_context::<AppState>(cx);
839 let viewer = require_admin_csrf(cx, &form.csrf).await?;
840 let sub = path_param_segment(cx, "sub").to_owned();
841 let bytes = match quota_bytes(&form.quota_mib) {
842 Ok(bytes) => bytes,
843 Err(error) => return refuse(error),
844 };
845 let Some(before) = state.store.member(&sub).await? else {
846 return Err(not_found().into());
847 };
848 if let Err(error) = state.store.set_quota(&sub, bytes).await {
849 return refuse(error);
850 }
851 audited(
852 state,
853 &viewer,
854 "quota.set",
855 "member",
856 &sub,
857 json!({ "from": before.quota_bytes, "to": bytes }),
858 )
859 .await;
860 Ok(see_other("/admin?notice=quota_saved"))
861}
862
863/// `POST /admin/services/{key}/quota`: sets a service's quota.
864#[route(POST "/admin/services/{key}/quota")]
865async fn set_service_quota(cx: &Cx, Form(form): Form<QuotaForm>) -> Result<SeeOther> {
866 let state = app_context::<AppState>(cx);
867 let viewer = require_admin_csrf(cx, &form.csrf).await?;
868 let key = path_param_segment(cx, "key").to_owned();
869 let bytes = match quota_bytes(&form.quota_mib) {
870 Ok(bytes) => bytes,
871 Err(error) => return refuse(error),
872 };
873 let Some(before) = state.store.service(&key).await? else {
874 return Err(not_found().into());
875 };
876 if let Err(error) = state.store.set_service_quota(&key, bytes).await {
877 return refuse(error);
878 }
879 audited(
880 state,
881 &viewer,
882 "service.quota.set",
883 "service",
884 &key,
885 json!({ "from": before.quota_bytes, "to": bytes }),
886 )
887 .await;
888 Ok(see_other("/admin?notice=service_quota_saved"))
889}
890
891/// Validates every default before writing any of them, then writes the changed ones, each audited.
892async fn apply_defaults(
893 state: &AppState,
894 viewer: &Viewer,
895 form: &DefaultsForm,
896) -> std::result::Result<(), CoreError> {
897 let inputs = [
898 (DEFAULT_QUOTA_KEY, form.default_quota_mib.as_str()),
899 (
900 DEFAULT_SERVICE_QUOTA_KEY,
901 form.default_service_quota_mib.as_str(),
902 ),
903 (PURGE_KEY, form.purge_after_days.as_str()),
904 (MAX_UPLOAD_KEY, form.max_upload_mib.as_str()),
905 (LINK_MAX_DAYS_KEY, form.link_max_days.as_str()),
906 ];
907 let mut parsed = Vec::with_capacity(inputs.len());
908 for (key, text) in inputs {
909 let text = if is_mib(key) {
910 mib_to_text(text)?
911 } else {
912 text.trim().to_owned()
913 };
914 parsed.push((key, settings::parse_ui(key, &text)?));
915 }
916 for (key, new) in parsed {
917 let current = state
918 .store
919 .get_setting(key)
920 .await?
921 .and_then(|text| text.trim().parse::<i64>().ok());
922 if current == new {
923 continue;
924 }
925 match new {
926 Some(value) => {
927 state.store.set_setting(key, &value.to_string()).await?;
928 audited(
929 state,
930 viewer,
931 "setting.set",
932 "setting",
933 key,
934 json!({ "value": value }),
935 )
936 .await;
937 }
938 None => {
939 state.store.clear_setting(key).await?;
940 audited(state, viewer, "setting.clear", "setting", key, json!({})).await;
941 }
942 }
943 }
944 Ok(())
945}
946
947/// `POST /admin/defaults`: sets or clears the UI overrides of the five defaults.
948#[route(POST "/admin/defaults")]
949async fn save_defaults(cx: &Cx, Form(form): Form<DefaultsForm>) -> Result<SeeOther> {
950 let state = app_context::<AppState>(cx);
951 let viewer = require_admin_csrf(cx, &form.csrf).await?;
952 match apply_defaults(state, &viewer, &form).await {
953 Ok(()) => Ok(see_other("/admin?notice=defaults_saved")),
954 Err(error) => refuse(error),
955 }
956}
957
958/// `POST /admin/backup`: asks the backup worker for a backup now. Refused when backups are off. The administrator
959/// and the CSRF token are checked first. A request made while a run is pending or running starts nothing, and
960/// gets the same notice. The request is audited.
961#[route(POST "/admin/backup")]
962async fn back_up_now(cx: &Cx, Form(form): Form<BackupForm>) -> Result<SeeOther> {
963 let state = app_context::<AppState>(cx);
964 let viewer = require_admin_csrf(cx, &form.csrf).await?;
965 if state.config.backup.is_none() {
966 return Ok(see_other(with_param("/admin", "refusal", "backup_off")));
967 }
968 let started = state.backup.request();
969 audit::record(
970 state,
971 Entry {
972 actor: Some(&viewer.member.sub),
973 action: "backup.requested",
974 target_kind: "backup",
975 target_id: None,
976 data: json!({ "started": started }),
977 },
978 )
979 .await;
980 Ok(see_other("/admin?notice=backup_started"))
981}
982
983/// `GET /live/admin`: a data-less `changed` event whenever an audit entry is written. It ends when the viewer
984/// is no longer an administrator.
985#[route(GET "/live/admin")]
986async fn admin_live(cx: &Cx) -> Result<Response> {
987 let state = app_context::<AppState>(cx);
988 let viewer = require_admin(cx).await?;
989 let sub = viewer.member.sub.clone();
990 let store: Store = state.store.clone();
991 stream_changes(cx, &state.live, &[Topic::AdminAudit], move || {
992 let store = store.clone();
993 let sub = sub.clone();
994 async move {
995 match store.member(&sub).await? {
996 Some(member) if member.is_admin && !member.disabled => {}
997 _ => return Err(not_found().into()),
998 }
999 Ok(store.latest_audit_id().await?.unwrap_or_default())
1000 }
1001 })
1002 .await
1003}
1004
1005#[cfg(test)]
1006mod tests {
1007 use http::header::{CONTENT_TYPE, COOKIE};
1008 use in_core::store::members::MemberFields;
1009 use topcoat::router::Body;
1010
1011 use super::*;
1012 use crate::auth::SESSION_COOKIE;
1013 use crate::auth::test_support::signed_in;
1014 use crate::boot::{router, test_state};
1015
1016 /// Makes `sub` an administrator as well, through the same write the sign-in uses.
1017 async fn make_admin(state: &AppState, sub: &str) {
1018 state
1019 .store
1020 .upsert_member_from_claims(
1021 &MemberFields {
1022 sub: sub.into(),
1023 email: format!("{sub}@example.test"),
1024 name: sub.into(),
1025 is_admin: true,
1026 locale: "en".into(),
1027 zoneinfo: "UTC".into(),
1028 picture_version: 0,
1029 im_updated_at: String::new(),
1030 },
1031 in_core::quota::DEFAULT_MEMBER_QUOTA,
1032 )
1033 .await
1034 .expect("admin");
1035 }
1036
1037 #[tokio::test]
1038 async fn a_member_who_is_not_an_administrator_gets_404_on_the_admin_page() {
1039 let (_dir, state) = test_state().await;
1040 let token = signed_in(&state, "ann", in_core::quota::DEFAULT_MEMBER_QUOTA).await;
1041 let request = http::Request::get("/admin")
1042 .header(COOKIE, format!("{SESSION_COOKIE}={token}"))
1043 .body(Body::empty())
1044 .expect("request");
1045 let response = router(state).handle(request).await;
1046 assert_eq!(response.status(), 404);
1047 }
1048
1049 #[tokio::test]
1050 async fn an_admin_quota_write_without_the_csrf_token_is_refused_and_changes_nothing() {
1051 let (_dir, state) = test_state().await;
1052 let token = signed_in(&state, "ann", in_core::quota::DEFAULT_MEMBER_QUOTA).await;
1053 make_admin(&state, "ann").await;
1054 let before = state
1055 .store
1056 .member("ann")
1057 .await
1058 .unwrap()
1059 .unwrap()
1060 .quota_bytes;
1061 let request = http::Request::post("/admin/people/ann/quota")
1062 .header(COOKIE, format!("{SESSION_COOKIE}={token}"))
1063 .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
1064 .body(Body::from("quota_mib=1"))
1065 .expect("request");
1066 let response = router(state.clone()).handle(request).await;
1067 assert_eq!(response.status(), 403);
1068 let after = state
1069 .store
1070 .member("ann")
1071 .await
1072 .unwrap()
1073 .unwrap()
1074 .quota_bytes;
1075 assert_eq!(before, after);
1076 }
1077}