//! The administration page (`GET /admin`) and its writes. Only an instance administrator (the `im_admin` //! claim, stored as `members.is_admin`) sees it. Anyone else gets `404`, and so does a write from them. //! //! The page shows: health (the database and the blob store answer), the storage backend and its free space //! or reachability, the backup schedule with the last success and attempt, an alert for a failed latest run, //! a warning when no success is recent, and a button that asks for a backup now, the base URL, every person //! with their quota, every service with its usage and quota, the defaults with the layer each value comes from //! (UI, file or built-in default), and the audit log with keyset paging and filters. //! //! Every write is checked (administrator, then CSRF, both before any side effect), validated, and then //! audited after it commits. The audit writer never fails a request. The defaults form is all-or-nothing: if //! one value is out of range, nothing is written. A backup request only wakes the backup worker: the run itself //! happens in the background, and a request made while one is pending or running starts nothing. use std::time::Duration; use in_core::config::Backend; use in_core::error::Error as CoreError; use in_core::settings::{ self, DEFAULT_QUOTA_KEY, DEFAULT_SERVICE_QUOTA_KEY, FIELDS, LINK_MAX_DAYS_KEY, MAX_UPLOAD_KEY, Mode, PURGE_KEY, Source, }; use in_core::store::audit::{AuditQuery, AuditRow}; use in_core::store::members::Member; use in_core::store::objects::Service; use in_core::store::{Store, objects::Usage}; 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, see_other}; use topcoat::router::response::Response; use topcoat::router::{page, parse_query_params, path_param_segment, route}; use topcoat::view::{View, component, view}; use crate::audit::{self, Entry}; use crate::auth::{Viewer, require_admin, require_admin_csrf}; use crate::backup::{LAST_ATTEMPT_AT, LAST_ERROR, LAST_SUCCESS_AT, is_stale}; use crate::health::{probe_blobs, probe_database}; use crate::i18n::Lang; use crate::i18n::admin::{AK, a, backup_failed, backup_schedule, notice, refusal}; use crate::live::{Topic, stream_changes}; use crate::oidc::percent_encode; use crate::pages::drive::{viewer_lang, with_param}; use crate::state::AppState; use crate::views::drive::{size_text, stamp_text}; use crate::views::{ViewerInfo, alert, notice as flash_notice, shell, warning}; /// One mebibyte, the unit of the admin's byte fields. const MIB: i64 = 1024 * 1024; /// Audit rows per page. pub const AUDIT_PAGE: usize = 50; /// How long a probe of the blob store may take on this page. A slow bucket shows as not reachable. const PROBE_WAIT: Duration = Duration::from_secs(2); /// The query of the page: notice and refusal words, the audit filters and the keyset cursor. #[derive(Debug, Default, Deserialize)] #[serde(default)] pub struct AdminQuery { /// A word from a successful write. pub notice: String, /// A word from a refused write. pub refusal: String, /// Exact action filter. pub action: String, /// Exact actor id filter. pub actor: String, /// Exact target kind filter. pub target: String, /// Cursor `at|id` of the last row of the previous page. pub before: String, } /// The form of a quota write: the CSRF token and the quota in MiB. #[derive(Debug, Default, Deserialize)] #[serde(default)] pub struct QuotaForm { /// The CSRF token of the session. pub csrf: String, /// The new quota, in MiB. pub quota_mib: String, } /// The form of the defaults. Every field is optional on the wire; blank clears the UI override. #[derive(Debug, Default, Deserialize)] #[serde(default)] pub struct DefaultsForm { /// The CSRF token of the session. pub csrf: String, /// New person's quota, MiB. pub default_quota_mib: String, /// New service's quota, MiB. pub default_service_quota_mib: String, /// Days before a purge. pub purge_after_days: String, /// Largest upload, MiB. pub max_upload_mib: String, /// Longest share link, days. pub link_max_days: String, } /// One row of the defaults table. #[derive(Debug, Clone)] pub struct DefaultRow { /// Form field name. pub field: &'static str, /// Heading of the row. pub label: AK, /// The UI override in the form's unit, blank when none is set. pub input: String, /// The effective value, formatted. pub shown: String, /// Where the effective value comes from. pub source: Source, /// How the value may change. pub mode: Mode, } /// What the page shows about the storage backend. #[derive(Debug, Clone)] pub struct StorageStatus { /// `local` or `s3`. pub backend: &'static str, /// The local blob path, or the bucket name. pub location: String, /// Free bytes on the local path, when it could be read. pub free: Option, /// Whether the S3 bucket answered a probe. pub reachable: Option, /// The base URL from the file. pub base_url: String, } /// The health probes: whether each part answered. #[derive(Debug, Clone, Copy)] pub struct Probes { /// The database answered a `SELECT 1`. pub database: bool, /// The blob store answered. pub blobs: bool, } /// The form of the backup button: only the CSRF token of the session. #[derive(Debug, Default, Deserialize)] #[serde(default)] pub struct BackupForm { /// The CSRF token of the session. pub csrf: String, } /// What the backups section shows: where the sets go, how often a run happens, and the outcome the worker /// recorded. `None` when the configuration has no `[backup]` table. #[derive(Debug, Clone)] pub struct BackupStatus { /// The directory that receives the sets. pub dir: String, /// Hours between scheduled runs. pub interval_hours: u32, /// Sets kept. pub keep: u32, /// When a run was last attempted, if one ran. pub last_attempt: Option, /// When a run last succeeded, if one did. pub last_success: Option, /// The short error of the latest run, present only while that run failed. pub last_error: Option, /// True when no success is recent enough (see `backup::is_stale`). pub stale: bool, } /// The backups section's data: the configuration and what the worker recorded. `None` when backups are off. async fn backup_status(state: &AppState) -> Result> { let Some(config) = state.config.backup.as_ref() else { return Ok(None); }; let last_success = state.store.get_setting(LAST_SUCCESS_AT).await?; Ok(Some(BackupStatus { dir: config.dir.display().to_string(), interval_hours: config.interval_hours, keep: config.keep, last_attempt: state.store.get_setting(LAST_ATTEMPT_AT).await?, stale: is_stale(last_success.as_deref(), config.interval_hours), last_success, last_error: state .store .get_setting(LAST_ERROR) .await? .filter(|error| !error.is_empty()), })) } /// Whether a field's form unit is MiB. fn is_mib(key: &str) -> bool { key == DEFAULT_QUOTA_KEY || key == DEFAULT_SERVICE_QUOTA_KEY || key == MAX_UPLOAD_KEY } /// The form field name of a runtime setting. fn field_name(key: &str) -> &'static str { match key { DEFAULT_QUOTA_KEY => "default_quota_mib", DEFAULT_SERVICE_QUOTA_KEY => "default_service_quota_mib", PURGE_KEY => "purge_after_days", MAX_UPLOAD_KEY => "max_upload_mib", _ => "link_max_days", } } /// The label heading of a runtime setting. fn label_of(key: &str) -> AK { match key { DEFAULT_QUOTA_KEY => AK::DefaultQuotaLabel, DEFAULT_SERVICE_QUOTA_KEY => AK::DefaultServiceQuotaLabel, PURGE_KEY => AK::PurgeLabel, MAX_UPLOAD_KEY => AK::MaxUploadLabel, _ => AK::LinkMaxLabel, } } /// Converts a MiB figure from a form to bytes. Blank is "no value" and is passed through as blank. fn mib_to_text(text: &str) -> std::result::Result { let text = text.trim(); if text.is_empty() { return Ok(String::new()); } text.parse::() .ok() .and_then(|mib| mib.checked_mul(MIB)) .map(|bytes| bytes.to_string()) .ok_or_else(|| CoreError::Invalid("quota_range".into())) } /// The bytes of a person's or a service's quota from its form: required, and within the field's bounds. fn quota_bytes(text: &str) -> std::result::Result { let text = mib_to_text(text)?; let field = settings::field(DEFAULT_QUOTA_KEY) .ok_or_else(|| CoreError::Invalid("quota_range".into()))?; let bytes: i64 = text .parse() .map_err(|_| CoreError::Invalid("quota_range".into()))?; settings::check(field, bytes).map_err(|_| CoreError::Invalid("quota_range".into())) } /// Maps a refused write to the answer: a missing item is `404`, a refusal goes back to the page with its /// word, anything else is a server error. fn refuse(error: CoreError) -> Result { match error { CoreError::NotFound => Err(not_found().into()), CoreError::Invalid(word) | CoreError::Conflict(word) | CoreError::Forbidden(word) => { let safe = if word.chars().all(|c| c.is_ascii_lowercase() || c == '_') { word } else { "generic".to_owned() }; Ok(see_other(with_param("/admin", "refusal", &safe))) } other => Err(other.into()), } } /// Appends one audit entry for a change made by `actor`. async fn audited( state: &AppState, actor: &Viewer, action: &str, target_kind: &str, target_id: &str, data: serde_json::Value, ) { audit::record( state, Entry { actor: Some(&actor.member.sub), action, target_kind, target_id: Some(target_id), data, }, ) .await; } /// The rows of the defaults table: each field's effective value, its source and its mode. async fn default_rows(state: &AppState) -> Result> { let mut rows = Vec::with_capacity(FIELDS.len()); for field in &FIELDS { let resolved = settings::resolve(&state.store, &state.config.limits, field.key).await?; let ui = state .store .get_setting(field.key) .await? .and_then(|text| text.trim().parse::().ok()); let mib = is_mib(field.key); let input = match ui { Some(value) if mib => (value / MIB).to_string(), Some(value) => value.to_string(), None => String::new(), }; let shown = if mib { size_text(resolved.value) } else { resolved.value.to_string() }; rows.push(DefaultRow { field: field_name(field.key), label: label_of(field.key), input, shown, source: resolved.source, mode: field.mode, }); } Ok(rows) } /// What the storage section needs: the backend, its location and its free space or reachability. async fn storage_status(state: &AppState) -> StorageStatus { let base_url = state.config.base_url.clone(); match state.config.storage.backend { Backend::Local => { let path = state.config.data_dir.join(crate::boot::BLOB_DIR); StorageStatus { backend: "local", location: path.display().to_string(), free: free_space(&path), reachable: None, base_url, } } Backend::S3 => { let reachable = tokio::time::timeout(PROBE_WAIT, probe_blobs(state.blobs.as_ref())) .await .is_ok_and(|outcome| outcome.is_ok()); StorageStatus { backend: "s3", location: state .config .storage .s3 .as_ref() .map(|s3| s3.bucket.clone()) .unwrap_or_default(), free: None, reachable: Some(reachable), base_url, } } } } /// Free bytes available to this user on the filesystem of `path`, when it can be read. fn free_space(path: &std::path::Path) -> Option { let stat = rustix::fs::statvfs(path).ok()?; let bytes = u128::from(stat.f_bavail) * u128::from(stat.f_frsize); Some(i64::try_from(bytes).unwrap_or(i64::MAX)) } /// Both health probes, each within the probe deadline. async fn probe_all(state: &AppState) -> Probes { let (database, blobs) = tokio::join!( tokio::time::timeout(PROBE_WAIT, probe_database(state)), tokio::time::timeout(PROBE_WAIT, probe_blobs(state.blobs.as_ref())), ); Probes { database: database.is_ok_and(|r| r.is_ok()), blobs: blobs.is_ok_and(|r| r.is_ok()), } } /// Parses the `at|id` cursor. Anything malformed starts the log from the top. fn parse_cursor(raw: &str) -> Option<(String, String)> { let (at, id) = raw.split_once('|')?; (!at.is_empty() && !id.is_empty()).then(|| (at.to_owned(), id.to_owned())) } /// The link to the next page of the log, keeping the filters. fn older_link(query: &AdminQuery, last: &AuditRow) -> String { format!( "/admin?action={}&actor={}&target={}&before={}", percent_encode(&query.action), percent_encode(&query.actor), percent_encode(&query.target), percent_encode(&format!("{}|{}", last.at, last.id)), ) } /// The health line of one probe. #[component] async fn probe_line(lang: Lang, label: &str, ok: bool) -> Result { let word = if ok { a(lang, AK::HealthOk) } else { a(lang, AK::HealthFail) }; Ok(view! {
  • (label) ": " (word)
  • }) } /// The health section. #[component] async fn health_section(lang: Lang, probes: Probes, build_sha: &str) -> Result { Ok(view! {

    (a(lang, AK::Health))

      probe_line(lang: lang, label: a(lang, AK::Database), ok: probes.database) probe_line(lang: lang, label: a(lang, AK::Blobs), ok: probes.blobs)
    • (a(lang, AK::Build)) ": " (build_sha)
    }) } /// The storage and base URL section. #[component] async fn storage_section(lang: Lang, status: &StorageStatus) -> Result { let free = status .free .map_or_else(|| a(lang, AK::NotAvailable).to_owned(), size_text); let reach = match status.reachable { Some(true) => a(lang, AK::Reachable), Some(false) => a(lang, AK::Unreachable), None => a(lang, AK::NotAvailable), }; Ok(view! {

    (a(lang, AK::Storage))

    • (a(lang, AK::Backend)) ": " (status.backend)
    • (a(lang, AK::LocalPath)) ": " (status.location.as_str())
    • if status.backend == "local" {
    • (a(lang, AK::FreeSpace)) ": " (free.as_str())
    • } else {
    • (reach)
    • }

    (a(lang, AK::BaseUrl))

    (status.base_url.as_str()) " " (a(lang, AK::BaseUrlFile))

    }) } /// The backups section: the directory and schedule, the last success and attempt, an alert when the latest /// run failed, a warning when no success is recent, and the button that asks for a run now. Without /// `[backup]` it says that backups are off. #[component] async fn backup_section( lang: Lang, status: Option<&BackupStatus>, csrf: &str, ) -> Result { let schedule = status.map_or_else(String::new, |s| { backup_schedule(lang, s.interval_hours, s.keep) }); let dir = status.map_or_else(String::new, |s| s.dir.clone()); let never = || a(lang, AK::BackupNever).to_owned(); let last_success = status.and_then(|s| s.last_success.as_deref()); let last_success = last_success.map_or_else(never, stamp_text); let last_attempt = status.and_then(|s| s.last_attempt.as_deref()); let last_attempt = last_attempt.map_or_else(never, stamp_text); let failed = status .and_then(|s| s.last_error.as_deref()) .map(|error| backup_failed(lang, error)); let stale = status.is_some_and(|s| s.stale); Ok(view! {

    (a(lang, AK::Backups))

    if status.is_some() {
    • (a(lang, AK::BackupDir)) ": " (dir.as_str())
    • (schedule.as_str())
    • (a(lang, AK::BackupLast)) ": " (last_success.as_str())
    • (a(lang, AK::BackupAttempt)) ": " (last_attempt.as_str())
    if let Some(text) = failed.as_deref() { alert(message: text) } if stale { warning(message: a(lang, AK::BackupStale)) }
    } else {

    (a(lang, AK::BackupOff))

    }
    }) } /// One person in the people table, with the form that sets their quota. #[component] async fn person_row(lang: Lang, member: &Member, csrf: &str) -> Result { let action = format!("/admin/people/{}/quota", member.sub); let quota_mib = (member.quota_bytes / MIB).to_string(); let used = size_text(member.used_bytes); let quota = size_text(member.quota_bytes); let input_id = format!("q-{}", member.sub); Ok(view! { (member.name.as_str()) if member.is_admin { " " (a(lang, AK::AdminBadge)) } if member.disabled { " " (a(lang, AK::DisabledBadge)) } (member.email.as_str()) (used.as_str()) " / " (quota.as_str())
    }) } /// The people section. #[component] async fn people_section(lang: Lang, members: &[Member], csrf: &str) -> Result { Ok(view! {

    (a(lang, AK::People))

    for member in members { person_row(lang: lang, member: member, csrf: csrf) }
    (a(lang, AK::ColName)) (a(lang, AK::ColEmail)) (a(lang, AK::ColUsed)) " / " (a(lang, AK::ColQuota)) (a(lang, AK::ColSetQuota))
    }) } /// One service in the services table, with the form that sets its quota. #[component] async fn service_row( lang: Lang, service: &Service, usage: &Usage, csrf: &str, ) -> Result { let action = format!("/admin/services/{}/quota", service.key); let quota_mib = (usage.quota_bytes / MIB).to_string(); let used = size_text(usage.used_bytes); let quota = size_text(usage.quota_bytes); let objects = usage.objects.to_string(); let input_id = format!("s-{}", service.key); Ok(view! { (service.key.as_str()) (objects.as_str()) (used.as_str()) " / " (quota.as_str())
    }) } /// The services section. Each row carries its usage, read by the caller. #[component] async fn services_section(lang: Lang, rows: &[(Service, Usage)], csrf: &str) -> Result { Ok(view! {

    (a(lang, AK::Services))

    if rows.is_empty() {

    (a(lang, AK::ServicesEmpty))

    } else { for (service, usage) in rows { service_row(lang: lang, service: service, usage: usage, csrf: csrf) }
    "key" (a(lang, AK::ColObjects)) (a(lang, AK::ColUsed)) " / " (a(lang, AK::ColQuota)) (a(lang, AK::ColSetQuota))
    }
    }) } /// One row of the defaults table: the field, the value in effect, its source, its mode and the input. #[component] async fn default_field(lang: Lang, row: &DefaultRow) -> Result { let source = match row.source { Source::Ui => a(lang, AK::SourceUi), Source::File => a(lang, AK::SourceFile), Source::Default => a(lang, AK::SourceDefault), }; let mode = match row.mode { Mode::Live => a(lang, AK::ModeLive), Mode::Restart => a(lang, AK::ModeRestart), Mode::ReadOnly => a(lang, AK::ModeReadOnly), }; let input_id = format!("d-{}", row.field); Ok(view! { (row.shown.as_str()) (source) (mode) }) } /// The defaults section: the form of the five defaults. #[component] async fn defaults_section(lang: Lang, rows: &[DefaultRow], csrf: &str) -> Result { Ok(view! {

    (a(lang, AK::Defaults))

    (a(lang, AK::DefaultsHint))

    for row in rows { default_field(lang: lang, row: row) }
    (a(lang, AK::ColName)) (a(lang, AK::ColValue)) "=" (a(lang, AK::ColSource)) (a(lang, AK::ColMode))
    }) } /// One audit row: when, who, what, to what, and the details. #[component] async fn audit_row(row: &AuditRow) -> Result { let when = stamp_text(&row.at); let actor = match &row.actor_id { Some(id) => format!("{} {id}", row.actor_kind), None => row.actor_kind.clone(), }; let target = match &row.target_id { Some(id) => format!("{} {id}", row.target_kind), None => row.target_kind.clone(), }; Ok(view! { (when.as_str()) (actor.as_str()) (row.action.as_str()) (target.as_str()) (row.data.as_str()) }) } /// The audit section: the filters, the page of rows and the link to the next page. #[component] async fn audit_section( lang: Lang, rows: &[AuditRow], action: &str, actor: &str, target: &str, older: Option<&str>, ) -> Result { Ok(view! {

    (a(lang, AK::Audit))

    if rows.is_empty() {

    (a(lang, AK::AuditEmpty))

    } else { for row in rows { audit_row(row: row) }
    (a(lang, AK::ColAt)) (a(lang, AK::ColActor)) (a(lang, AK::ColAction)) (a(lang, AK::ColTarget)) (a(lang, AK::ColDetails))
    } if let Some(link) = older {

    (a(lang, AK::OlderEntries))

    }
    }) } /// The whole page body: the notice or refusal, then the sections. #[allow(clippy::too_many_arguments)] // The page has this many separate parts; a struct would only hide them. #[component] async fn admin_body( lang: Lang, csrf: &str, flash: Option<&str>, refusal_text: Option<&str>, probes: Probes, build_sha: &str, storage: &StorageStatus, backups: Option<&BackupStatus>, members: &[Member], services: &[(Service, Usage)], defaults: &[DefaultRow], audit_rows: &[AuditRow], filters: (&str, &str, &str), older: Option<&str>, ) -> Result { Ok(view! {

    (a(lang, AK::Title))

    (a(lang, AK::Hint))

    if let Some(text) = flash { flash_notice(message: text) } if let Some(text) = refusal_text { alert(message: text) } health_section(lang: lang, probes: probes, build_sha: build_sha) storage_section(lang: lang, status: storage) backup_section(lang: lang, status: backups, csrf: csrf) people_section(lang: lang, members: members, csrf: csrf) services_section(lang: lang, rows: services, csrf: csrf) defaults_section(lang: lang, rows: defaults, csrf: csrf) audit_section(lang: lang, rows: audit_rows, action: filters.0, actor: filters.1, target: filters.2, older: older)
    }) } /// `GET /admin`. #[page("/admin")] async fn admin_page(cx: &Cx) -> Result { let state = app_context::(cx); let viewer = require_admin(cx).await?; let lang = viewer_lang(cx, &viewer); let query: AdminQuery = parse_query_params(cx).unwrap_or_default(); let members = state.store.list_members().await?; let mut services = Vec::new(); for service in state.store.services().await? { let usage = state.store.service_usage(&service.key).await?; services.push((service, usage)); } let defaults = default_rows(state).await?; let storage = storage_status(state).await; let backups = backup_status(state).await?; let probes = probe_all(state).await; let page = state .store .audit_page(&AuditQuery { action: query.action.trim().to_owned(), actor_id: query.actor.trim().to_owned(), target_kind: query.target.trim().to_owned(), before: parse_cursor(&query.before), limit: AUDIT_PAGE + 1, }) .await?; let has_more = page.len() > AUDIT_PAGE; let shown: Vec = page.into_iter().take(AUDIT_PAGE).collect(); let older = if has_more { shown.last().map(|last| older_link(&query, last)) } else { None }; let flash = (!query.notice.is_empty()) .then(|| notice(lang, &query.notice)) .flatten(); let refusal_text = (!query.refusal.is_empty()).then(|| refusal(lang, &query.refusal)); let info = ViewerInfo::of(&viewer, state.family.list()); let build = env!("IN_BUILD_SHA"); Ok(view! { shell(title: a(lang, AK::Title), lang: lang, viewer: Some(&info), admin_body( lang: lang, csrf: viewer.session.csrf_token.as_str(), flash: flash, refusal_text: refusal_text, probes: probes, build_sha: build, storage: &storage, backups: backups.as_ref(), members: &members, services: &services, defaults: &defaults, audit_rows: &shown, filters: (query.action.trim(), query.actor.trim(), query.target.trim()), older: older.as_deref(), ) ) }) } /// `POST /admin/people/{sub}/quota`: sets a person's quota. The administrator and the CSRF token are checked /// first; the change is audited after it commits. #[route(POST "/admin/people/{sub}/quota")] async fn set_person_quota(cx: &Cx, Form(form): Form) -> Result { let state = app_context::(cx); let viewer = require_admin_csrf(cx, &form.csrf).await?; let sub = path_param_segment(cx, "sub").to_owned(); let bytes = match quota_bytes(&form.quota_mib) { Ok(bytes) => bytes, Err(error) => return refuse(error), }; let Some(before) = state.store.member(&sub).await? else { return Err(not_found().into()); }; if let Err(error) = state.store.set_quota(&sub, bytes).await { return refuse(error); } audited( state, &viewer, "quota.set", "member", &sub, json!({ "from": before.quota_bytes, "to": bytes }), ) .await; Ok(see_other("/admin?notice=quota_saved")) } /// `POST /admin/services/{key}/quota`: sets a service's quota. #[route(POST "/admin/services/{key}/quota")] async fn set_service_quota(cx: &Cx, Form(form): Form) -> Result { let state = app_context::(cx); let viewer = require_admin_csrf(cx, &form.csrf).await?; let key = path_param_segment(cx, "key").to_owned(); let bytes = match quota_bytes(&form.quota_mib) { Ok(bytes) => bytes, Err(error) => return refuse(error), }; let Some(before) = state.store.service(&key).await? else { return Err(not_found().into()); }; if let Err(error) = state.store.set_service_quota(&key, bytes).await { return refuse(error); } audited( state, &viewer, "service.quota.set", "service", &key, json!({ "from": before.quota_bytes, "to": bytes }), ) .await; Ok(see_other("/admin?notice=service_quota_saved")) } /// Validates every default before writing any of them, then writes the changed ones, each audited. async fn apply_defaults( state: &AppState, viewer: &Viewer, form: &DefaultsForm, ) -> std::result::Result<(), CoreError> { let inputs = [ (DEFAULT_QUOTA_KEY, form.default_quota_mib.as_str()), ( DEFAULT_SERVICE_QUOTA_KEY, form.default_service_quota_mib.as_str(), ), (PURGE_KEY, form.purge_after_days.as_str()), (MAX_UPLOAD_KEY, form.max_upload_mib.as_str()), (LINK_MAX_DAYS_KEY, form.link_max_days.as_str()), ]; let mut parsed = Vec::with_capacity(inputs.len()); for (key, text) in inputs { let text = if is_mib(key) { mib_to_text(text)? } else { text.trim().to_owned() }; parsed.push((key, settings::parse_ui(key, &text)?)); } for (key, new) in parsed { let current = state .store .get_setting(key) .await? .and_then(|text| text.trim().parse::().ok()); if current == new { continue; } match new { Some(value) => { state.store.set_setting(key, &value.to_string()).await?; audited( state, viewer, "setting.set", "setting", key, json!({ "value": value }), ) .await; } None => { state.store.clear_setting(key).await?; audited(state, viewer, "setting.clear", "setting", key, json!({})).await; } } } Ok(()) } /// `POST /admin/defaults`: sets or clears the UI overrides of the five defaults. #[route(POST "/admin/defaults")] async fn save_defaults(cx: &Cx, Form(form): Form) -> Result { let state = app_context::(cx); let viewer = require_admin_csrf(cx, &form.csrf).await?; match apply_defaults(state, &viewer, &form).await { Ok(()) => Ok(see_other("/admin?notice=defaults_saved")), Err(error) => refuse(error), } } /// `POST /admin/backup`: asks the backup worker for a backup now. Refused when backups are off. The administrator /// and the CSRF token are checked first. A request made while a run is pending or running starts nothing, and /// gets the same notice. The request is audited. #[route(POST "/admin/backup")] async fn back_up_now(cx: &Cx, Form(form): Form) -> Result { let state = app_context::(cx); let viewer = require_admin_csrf(cx, &form.csrf).await?; if state.config.backup.is_none() { return Ok(see_other(with_param("/admin", "refusal", "backup_off"))); } let started = state.backup.request(); audit::record( state, Entry { actor: Some(&viewer.member.sub), action: "backup.requested", target_kind: "backup", target_id: None, data: json!({ "started": started }), }, ) .await; Ok(see_other("/admin?notice=backup_started")) } /// `GET /live/admin`: a data-less `changed` event whenever an audit entry is written. It ends when the viewer /// is no longer an administrator. #[route(GET "/live/admin")] async fn admin_live(cx: &Cx) -> Result { let state = app_context::(cx); let viewer = require_admin(cx).await?; let sub = viewer.member.sub.clone(); let store: Store = state.store.clone(); stream_changes(cx, &state.live, &[Topic::AdminAudit], move || { let store = store.clone(); let sub = sub.clone(); async move { match store.member(&sub).await? { Some(member) if member.is_admin && !member.disabled => {} _ => return Err(not_found().into()), } Ok(store.latest_audit_id().await?.unwrap_or_default()) } }) .await } #[cfg(test)] mod tests { use http::header::{CONTENT_TYPE, COOKIE}; use in_core::store::members::MemberFields; use topcoat::router::Body; use super::*; use crate::auth::SESSION_COOKIE; use crate::auth::test_support::signed_in; use crate::boot::{router, test_state}; /// Makes `sub` an administrator as well, through the same write the sign-in uses. async fn make_admin(state: &AppState, sub: &str) { state .store .upsert_member_from_claims( &MemberFields { sub: sub.into(), email: format!("{sub}@example.test"), name: sub.into(), is_admin: true, locale: "en".into(), zoneinfo: "UTC".into(), picture_version: 0, im_updated_at: String::new(), }, in_core::quota::DEFAULT_MEMBER_QUOTA, ) .await .expect("admin"); } #[tokio::test] async fn a_member_who_is_not_an_administrator_gets_404_on_the_admin_page() { let (_dir, state) = test_state().await; let token = signed_in(&state, "ann", in_core::quota::DEFAULT_MEMBER_QUOTA).await; let request = http::Request::get("/admin") .header(COOKIE, format!("{SESSION_COOKIE}={token}")) .body(Body::empty()) .expect("request"); let response = router(state).handle(request).await; assert_eq!(response.status(), 404); } #[tokio::test] async fn an_admin_quota_write_without_the_csrf_token_is_refused_and_changes_nothing() { let (_dir, state) = test_state().await; let token = signed_in(&state, "ann", in_core::quota::DEFAULT_MEMBER_QUOTA).await; make_admin(&state, "ann").await; let before = state .store .member("ann") .await .unwrap() .unwrap() .quota_bytes; let request = http::Request::post("/admin/people/ann/quota") .header(COOKIE, format!("{SESSION_COOKIE}={token}")) .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .body(Body::from("quota_mib=1")) .expect("request"); let response = router(state.clone()).handle(request).await; assert_eq!(response.status(), 403); let after = state .store .member("ann") .await .unwrap() .unwrap() .quota_bytes; assert_eq!(before, after); } }