forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

message.rs159 lines, 6.0 KiBHistoryRawDownload
1//! `/admin/message`: a message from the administrator to every enabled account.
2//!
3//! The message is queued as one mail per account, in that account's language, through the same outbox as
4//! every other mail. The subject is one line of at most 150 characters; the body is at most 10 000
5//! characters, and blank lines separate its paragraphs. Each send counts against a small rate limit, so a
6//! form that is submitted again and again cannot queue thousands of mails.
7
8use std::time::Instant;
9
10use im_core::model::AuditAction;
11use im_core::names::{multi_line, single_line};
12use serde::Deserialize;
13use serde_json::json;
14use topcoat::Result;
15use topcoat::context::{Cx, app_context};
16use topcoat::router::content::Form;
17use topcoat::router::error::SeeOther;
18use topcoat::router::{page, route};
19use topcoat::view::{View, view};
20
21use crate::audit::{Actor, record};
22use crate::auth::{require_admin, require_admin_csrf};
23use crate::i18n::Lang;
24use crate::i18n::admin::{A, text};
25use crate::mail::{self, Mail, Recipient};
26use crate::pages::admin::{
27 FlashQuery, Tab, changed, done, error_text, flash_messages, frame_info, notice_text, refused,
28 tabs,
29};
30use crate::state::AppState;
31use crate::views::{ViewerInfo, field, page_lang, shell};
32
33/// The longest subject, in characters.
34const SUBJECT_MAX: usize = 150;
35
36/// The longest body, in characters.
37const BODY_MAX: usize = 10_000;
38
39/// Sends that the limit allows in one window of the throttle.
40const SENDS_PER_WINDOW: usize = 5;
41
42/// Path of the message form. The router raises the body limit for this path (see `boot.rs`).
43pub const MESSAGE_ROUTE: &str = "/admin/message";
44
45/// The body limit of the message form: every character of the subject and the body at its longest
46/// encoding (4 bytes of UTF-8, 3 bytes each once percent-encoded), plus room for the field names and the
47/// CSRF token. Smaller would refuse a long Turkish or CJK message before its own length check runs.
48pub const MESSAGE_BODY_LIMIT: usize = (SUBJECT_MAX + BODY_MAX) * 4 * 3 + 4 * 1024;
49
50/// The throttle key of the message form.
51const THROTTLE_KEY: &str = "admin-message";
52
53/// The message form.
54#[derive(Deserialize, Default)]
55struct MessageForm {
56 #[serde(default)]
57 csrf: String,
58 #[serde(default, deserialize_with = "single_line")]
59 subject: String,
60 #[serde(default, deserialize_with = "multi_line")]
61 body: String,
62}
63
64/// `GET /admin/message`.
65#[page("/admin/message")]
66async fn message_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl View> {
67 let viewer = require_admin(cx).await?;
68 let (lang, info) = frame_info(cx, &viewer);
69 Ok(message_view(
70 cx,
71 lang,
72 info,
73 viewer.session.csrf_token.clone(),
74 notice_text(lang, &query.notice).map(str::to_owned),
75 error_text(lang, &query.error).map(str::to_owned),
76 ))
77}
78
79/// `POST /admin/message`: queues the message for every enabled account.
80#[route(POST "/admin/message")]
81async fn send_message(cx: &Cx, Form(form): Form<MessageForm>) -> Result<SeeOther> {
82 let viewer = require_admin_csrf(cx, &form.csrf).await?;
83 let state = app_context::<AppState>(cx);
84 let subject = form.subject.trim();
85 let body = form.body.replace("\r\n", "\n");
86 let body = body.trim();
87 if subject.is_empty() || body.is_empty() {
88 return Ok(refused("/admin/message", "message-empty"));
89 }
90 if subject.chars().count() > SUBJECT_MAX || subject.contains(['\r', '\n']) {
91 return Ok(refused("/admin/message", "message-subject"));
92 }
93 if body.chars().count() > BODY_MAX {
94 return Ok(refused("/admin/message", "message-body"));
95 }
96 // Counted before the sends, so parallel submits cannot all pass the limit. A send is what is limited, so
97 // the count stays whatever the outcome.
98 if state
99 .throttle
100 .reserve(THROTTLE_KEY, SENDS_PER_WINDOW, Instant::now())
101 .is_err()
102 {
103 return Ok(refused("/admin/message", "rate-limited"));
104 }
105 let request = page_lang(cx, Some(&viewer));
106 let users = state.store.list_users(None, None, u32::MAX).await?;
107 let mut recipients = 0_usize;
108 for user in users.iter().filter(|user| user.disabled_at.is_none()) {
109 let Ok(to) = Recipient::new(Some(&user.name), &user.email) else {
110 tracing::error!(user = %user.id, "message not queued: stored address is not valid");
111 continue;
112 };
113 let lang = mail::lang_for(user, request);
114 let mail = Mail::Notice { subject, body };
115 mail::queue(&state.store, &state.key, &to, lang, &mail).await?;
116 recipients += 1;
117 }
118 record(
119 cx,
120 Actor::User(&viewer.user.id),
121 AuditAction::MessageSent,
122 None,
123 json!({ "recipients": recipients }),
124 )
125 .await;
126 changed(&state.live);
127 Ok(done("/admin/message", "message-sent"))
128}
129
130/// The message page: the subject and body fields, and the send button.
131fn message_view(
132 cx: &Cx,
133 lang: Lang,
134 info: ViewerInfo,
135 csrf: String,
136 success: Option<String>,
137 problem: Option<String>,
138) -> impl View {
139 view! { cx =>
140 shell(title: text(lang, A::MessageTitle), lang: lang, viewer: Some(info),
141 tabs(lang: lang, current: Tab::Message)
142 <section class="stack">
143 <h1>(text(lang, A::MessageTitle))</h1>
144 <p class="muted">(text(lang, A::MessageIntro))</p>
145 flash_messages(success: success, problem: problem)
146 <form method="post" action="/admin/message" class="stack">
147 <input type="hidden" name="csrf" value=(csrf)>
148 field(label: text(lang, A::MessageSubject), name: "subject", kind: "text", autocomplete: "off", value: String::new())
149 <label class="field">
150 <span class="field-label">(text(lang, A::MessageBody))</span>
151 <textarea name="body" rows="10"></textarea>
152 <span class="hint">(text(lang, A::MessageBodyHint))</span>
153 </label>
154 <button type="submit" class="button primary">(text(lang, A::MessageSend))</button>
155 </form>
156 </section>
157 )
158 }
159}