forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

mod.rs249 lines, 9.4 KiBHistoryRawDownload
1//! The administrator area: users, invitations, services and clients, mail, message, policy settings, signing
2//! keys, the audit log and health.
3//!
4//! Every page and every form here calls [`require_admin`] (or [`require_admin_csrf`] for a form). A member, or
5//! anyone signed out, gets the styled 404 before anything else happens, so the area does not reveal itself.
6//! A form also checks its CSRF token before any side effect, and answers 403 when the token is wrong.
7//!
8//! Writes redirect (Post/Redirect/Get) with a short code in the query string: `?notice=<code>` for success,
9//! `?error=<code>` for a refusal. The codes map to translated text in [`notice_text`] and [`error_text`]. A
10//! write that changes what an admin page shows calls [`changed`], which wakes the page's live stream
11//! (`/admin/events`). A write that changes what a person sees of their own account also bumps that account's
12//! topic, so their open pages refresh.
13
14pub mod audit;
15pub mod clients;
16pub mod health;
17pub mod invites;
18pub mod keys;
19pub mod mail;
20pub mod message;
21pub mod settings;
22pub mod users;
23
24#[cfg(test)]
25mod tests;
26
27use serde::Deserialize;
28use topcoat::Result;
29use topcoat::context::{Cx, app_context};
30use topcoat::router::error::{SeeOther, see_other};
31use topcoat::router::response::Response;
32use topcoat::router::route;
33use topcoat::view::{View, component, view};
34
35use crate::auth::require_admin;
36use crate::i18n::Lang;
37use crate::i18n::account::{Txt, text as account_text};
38use crate::i18n::admin::{A, text};
39use crate::live::{LiveHub, Topic, stream_changes};
40use crate::state::AppState;
41use crate::views::{ViewerInfo, alert, notice, page_lang};
42
43/// Rows per page of the long lists (users, mail, audit log).
44pub const PAGE_SIZE: u32 = 50;
45
46/// The query of every admin list and of the redirects after a write.
47#[derive(Deserialize, Default)]
48pub struct FlashQuery {
49 /// A success code, see [`notice_text`].
50 #[serde(default)]
51 pub notice: String,
52 /// A refusal code, see [`error_text`].
53 #[serde(default)]
54 pub error: String,
55}
56
57/// The tabs of the administrator area.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub enum Tab {
60 Users,
61 Invites,
62 Services,
63 Mail,
64 Message,
65 Settings,
66 Keys,
67 Audit,
68 Health,
69}
70
71/// The tab bar, with the current tab marked.
72#[component]
73pub async fn tabs(lang: Lang, current: Tab) -> Result<impl View> {
74 Ok(view! {
75 <nav class="tabs" aria-label=(account_text(lang, Txt::AdminArea))>
76 <a href="/admin/users" class=(tab_class(current, Tab::Users))>(text(lang, A::NavUsers))</a>
77 <a href="/admin/invites" class=(tab_class(current, Tab::Invites))>(text(lang, A::NavInvites))</a>
78 <a href="/admin/services" class=(tab_class(current, Tab::Services))>(text(lang, A::NavServices))</a>
79 <a href="/admin/mail" class=(tab_class(current, Tab::Mail))>(text(lang, A::NavMail))</a>
80 <a href="/admin/message" class=(tab_class(current, Tab::Message))>(text(lang, A::NavMessage))</a>
81 <a href="/admin/settings" class=(tab_class(current, Tab::Settings))>(text(lang, A::NavSettings))</a>
82 <a href="/admin/keys" class=(tab_class(current, Tab::Keys))>(text(lang, A::NavKeys))</a>
83 <a href="/admin/audit" class=(tab_class(current, Tab::Audit))>(text(lang, A::NavAudit))</a>
84 <a href="/admin/health" class=(tab_class(current, Tab::Health))>(text(lang, A::NavHealth))</a>
85 </nav>
86 })
87}
88
89/// The CSS class of one tab: the current one is marked for the screen reader and the style.
90fn tab_class(current: Tab, tab: Tab) -> &'static str {
91 if current == tab { "tab current" } else { "tab" }
92}
93
94/// Notifies the admin pages that something they show has changed. Call it after the write commits.
95pub fn changed(live: &LiveHub) {
96 live.bump(&Topic::Admin);
97}
98
99/// The text of a success code, or `None` for an unknown code (which is then ignored).
100pub fn notice_text(lang: Lang, code: &str) -> Option<&'static str> {
101 let key = match code {
102 "disabled" => A::NoticeDisabled,
103 "enabled" => A::NoticeEnabled,
104 "admin-granted" => A::NoticeAdminGranted,
105 "admin-removed" => A::NoticeAdminRemoved,
106 "2fa-reset" => A::NoticeTwoFactorReset,
107 "sessions-revoked" => A::NoticeSessionsRevoked,
108 "deleted" => A::NoticeDeleted,
109 "invite-revoked" => A::NoticeInviteRevoked,
110 "invite-resent" => A::NoticeInviteResent,
111 "invite-sent" => A::InviteQueued,
112 "client-saved" => A::ClientSaved,
113 "secret-rotated" => A::NoticeSecretRotated,
114 "client-disabled" => A::NoticeClientDisabled,
115 "mail-retried" => A::NoticeMailRetried,
116 "mail-abandoned" => A::NoticeMailAbandoned,
117 "test-queued" => A::NoticeTestQueued,
118 "settings-saved" => A::NoticeSettingsSaved,
119 "key-rotated" => A::NoticeKeyRotated,
120 "key-retired" => A::NoticeKeyRetired,
121 "file-value" => A::NoticeFileValue,
122 "message-sent" => A::NoticeMessageSent,
123 "backup-started" => A::NoticeBackupStarted,
124 _ => return None,
125 };
126 Some(text(lang, key))
127}
128
129/// The text of a refusal code, or `None` for an unknown code.
130pub fn error_text(lang: Lang, code: &str) -> Option<&'static str> {
131 let key = match code {
132 "last-admin" => A::ErrLastAdmin,
133 "self-disable" => A::ErrSelfDisable,
134 "self-admin" => A::ErrSelfAdmin,
135 "self-delete" => A::ErrSelfDelete,
136 "self" => A::NoOwnAccountHere,
137 "confirm-email" => A::ErrConfirmEmail,
138 "mail-retry" => A::ErrMailNotRetryable,
139 "mail-abandon" => A::ErrMailNotAbandonable,
140 "message-empty" => A::ErrMessageEmpty,
141 "message-subject" => A::ErrMessageSubjectLong,
142 "message-body" => A::ErrMessageBodyLong,
143 "message-email" => A::ErrMessageEmailInvalid,
144 "rate-limited" => A::ErrMessageRateLimited,
145 "key-current" => A::ErrKeyNotRetirable,
146 "backup-off" => A::ErrBackupOff,
147 "invite-gone" => A::ErrInviteGone,
148 "no-client" => A::ErrNoSuchClient,
149 "settings" => A::ErrSettingsInvalid,
150 "invite-taken" => A::ErrInviteTaken,
151 "email" => A::ErrInviteAddress,
152 "client-name" => A::ErrClientName,
153 "client-uri" => A::ErrUri,
154 "family-key" => A::ErrFamilyKey,
155 "family-taken" => A::ErrFamilyKeyTaken,
156 "public-url" => A::ErrPublicUrl,
157 "scopes" => A::ErrScopes,
158 _ => return None,
159 };
160 Some(text(lang, key))
161}
162
163/// `path?error=<code>`, the redirect of a refused write.
164pub fn refused(path: &str, code: &str) -> SeeOther {
165 see_other(format!("{path}?error={code}"))
166}
167
168/// `path?notice=<code>`, the redirect of a successful write.
169pub fn done(path: &str, code: &str) -> SeeOther {
170 see_other(format!("{path}?notice={code}"))
171}
172
173/// The viewer's info and language for an admin page, after the admin check.
174pub fn frame_info(cx: &Cx, viewer: &crate::auth::Viewer) -> (Lang, ViewerInfo) {
175 (page_lang(cx, Some(viewer)), ViewerInfo::of(viewer))
176}
177
178/// `GET /admin`: the first tab. Non-administrators get 404.
179#[route(GET "/admin")]
180async fn admin_root(cx: &Cx) -> Result<SeeOther> {
181 require_admin(cx).await?;
182 Ok(see_other("/admin/users"))
183}
184
185/// `GET /admin/events`: the live stream of the admin pages. It sends one `changed` event for each admin
186/// write, and the page fetches itself again. Non-administrators get 404.
187///
188/// The session and the administrator role are checked again on every wake, before an event is sent. A
189/// session that ended, or an account that lost the role or was disabled, ends the stream.
190#[route(GET "/admin/events")]
191async fn admin_events(cx: &Cx) -> Result<Response> {
192 let viewer = require_admin(cx).await?;
193 let state = app_context::<AppState>(cx);
194 let live = state.live.clone();
195 let store = state.store.clone();
196 let session_id = viewer.session.id.clone();
197 let user_id = viewer.user.id.clone();
198 stream_changes(cx, &state.live, &[Topic::Admin], move || {
199 let live = live.clone();
200 let store = store.clone();
201 let session_id = session_id.clone();
202 let user_id = user_id.clone();
203 async move {
204 let session_live = store.session_is_live(&session_id).await?;
205 let admin = store
206 .user_by_id(&user_id)
207 .await?
208 .is_some_and(|user| user.is_admin && !user.is_disabled());
209 if !(session_live && admin) {
210 return Err(topcoat::Error::msg(
211 "the administrator stream is no longer allowed",
212 ));
213 }
214 Ok(live.generation(&Topic::Admin).to_string())
215 }
216 })
217 .await
218}
219
220/// A form with one button, and the CSRF token. `on` is sent as a hidden field; it is empty for most actions.
221#[component]
222pub async fn action_button(
223 action: String,
224 csrf: String,
225 label: &'static str,
226 class: &'static str,
227 on: &'static str,
228) -> Result<impl View> {
229 Ok(view! {
230 <form method="post" action=(action) class="inline-form">
231 <input type="hidden" name="csrf" value=(csrf)>
232 <input type="hidden" name="on" value=(on)>
233 <button type="submit" class=(class)>(label)</button>
234 </form>
235 })
236}
237
238/// The success notice and the alert of an admin page, drawn above its content.
239#[component]
240pub async fn flash_messages(success: Option<String>, problem: Option<String>) -> Result<impl View> {
241 Ok(view! {
242 if let Some(message) = success {
243 notice(message: message)
244 }
245 if let Some(message) = problem {
246 alert(message: message)
247 }
248 })
249}