Skip to main content

tuwunel_service/admin/
respond.rs

1use futures::{FutureExt, TryStreamExt};
2use ruma::{
3	EventId, OwnedEventId, RoomId, UserId,
4	events::{
5		relation::{InReplyTo, Reply as ReplyRelation, Thread},
6		room::{
7			encrypted::Relation as EncryptedRelation,
8			message::{
9				Relation, RoomMessageEventContent, RoomMessageEventContentWithoutRelation,
10			},
11		},
12	},
13};
14use serde::Deserialize;
15use tuwunel_core::{
16	Error, Result, error,
17	error::default_log,
18	implement,
19	utils::{json::serialized_len, stream::IterStream, string::chunk},
20};
21use tuwunel_matrix::{
22	Event,
23	pdu::{MAX_PDU_BYTES, PduBuilder},
24};
25
26use super::{CommandOutput, notices::notice_markdown};
27use crate::rooms::state::RoomMutexGuard;
28
29/// Room event relation carried by an admin response.
30type MessageRelation = Relation<RoomMessageEventContentWithoutRelation>;
31
32/// Envelope overhead reserved above the message content: prev and auth event
33/// ids at their maximum, 255-byte sender and room ids, and the signatures
34/// block, just under 10 KiB in the worst legal case.
35const EVENT_RESERVE: usize = 10_240;
36
37/// Largest serialized message content that still fits a single event.
38const CONTENT_BUDGET: usize = MAX_PDU_BYTES - EVENT_RESERVE;
39
40/// Serialized size reserved for an `m.relates_to` relation carrying a
41/// maximum-length event id, so a segment measured without its relation still
42/// fits once the relation is attached.
43const RELATION_RESERVE: usize = 512;
44
45/// Largest serialized segment content, before its relation, that fits an event.
46const SEGMENT_BUDGET: usize = CONTENT_BUDGET - RELATION_RESERVE;
47
48/// How a command's output events relate back to the command event.
49enum Mode {
50	/// Thread children rooted at the given event (the command or its own
51	/// thread root).
52	Thread(OwnedEventId),
53
54	/// Replies: the first to the command, each subsequent to the one before it.
55	Reply(OwnedEventId),
56}
57
58#[derive(Deserialize)]
59struct ExtractRelatesTo {
60	#[serde(rename = "m.relates_to")]
61	relates_to: EncryptedRelation,
62}
63
64#[implement(super::Service)]
65pub(super) async fn handle_response(
66	&self,
67	output: CommandOutput,
68	reply_id: Option<&EventId>,
69) -> Result {
70	let Some(reply_id) = reply_id else {
71		return Ok(());
72	};
73
74	let Ok(pdu) = self.services.timeline.get_pdu(reply_id).await else {
75		error!(?reply_id, "Missing admin command in_reply_to event");
76		return Ok(());
77	};
78
79	let response_sender = if self.is_admin_room(pdu.room_id()).await {
80		&self.services.globals.server_user
81	} else {
82		pdu.sender()
83	};
84
85	let threads = self.services.server.config.admin.output_threads;
86	let mode = command_thread(&pdu)
87		.or_else(|| threads.then(|| reply_id.to_owned()))
88		.map_or_else(|| Mode::Reply(reply_id.to_owned()), Mode::Thread);
89
90	self.respond(&output, pdu.room_id(), response_sender, &mode)
91		.boxed() // size firewall
92		.await
93}
94
95/// Splits output across up to `admin.output_max_events` reply or thread events.
96///
97/// Output needing more events, or any output when the limit is zero, is uploaded
98/// and posted as a single file attachment instead.
99#[implement(super::Service)]
100async fn respond(
101	&self,
102	output: &CommandOutput,
103	room_id: &RoomId,
104	sender: &UserId,
105	mode: &Mode,
106) -> Result {
107	let markdown = matches!(output, CommandOutput::Markdown(_));
108	let max_events = self
109		.services
110		.server
111		.config
112		.admin
113		.output_max_events;
114
115	let segments = (max_events != 0)
116		.then(|| {
117			chunk(output.as_str(), markdown, |text: &str| fits_segment(text, markdown))
118				.take(max_events.saturating_add(1))
119				.collect::<Vec<_>>()
120		})
121		.filter(|segments| segments.len() <= max_events);
122
123	match segments {
124		| Some(segments) =>
125			self.send_segments(&segments, room_id, sender, mode, markdown)
126				.boxed() // size firewall
127				.await,
128		| None => {
129			let mut content = self.attach(output).await.unwrap_or_else(|e| {
130				error!(%e, "Failed to attach oversized admin command output");
131				notice(
132					&format!(
133						"Failed to attach command output: \"{e}\"\n\nThe original admin command \
134						 may have finished successfully, but we could not return the output."
135					),
136					markdown,
137				)
138			});
139
140			content.relates_to = Some(mode.relation(None));
141
142			self.respond_to_room(content, room_id, sender)
143				.boxed() // cold arm
144				.await
145		},
146	}
147}
148
149/// Appends every segment under one room lock, chaining each reply to the event
150/// id returned by the previous append.
151#[implement(super::Service)]
152async fn send_segments(
153	&self,
154	segments: &[String],
155	room_id: &RoomId,
156	sender: &UserId,
157	mode: &Mode,
158	markdown: bool,
159) -> Result {
160	assert!(self.user_is_admin(sender).await, "sender is not admin");
161
162	let state_lock = self.services.state.mutex.lock(room_id).await;
163
164	let result = segments
165		.iter()
166		.try_stream()
167		.try_fold(None, async |previous: Option<OwnedEventId>, segment| {
168			let mut content = notice(segment, markdown);
169			content.relates_to = Some(mode.relation(previous.as_deref()));
170
171			self.services
172				.timeline
173				.build_and_append_pdu(
174					PduBuilder::timeline(&content),
175					sender,
176					room_id,
177					&state_lock,
178				)
179				.await
180				.map(Some)
181		})
182		.await;
183
184	if let Err(e) = result {
185		self.handle_response_error(e, room_id, sender, &state_lock)
186			.boxed() // cold arm
187			.await
188			.unwrap_or_else(default_log);
189	}
190
191	Ok(())
192}
193
194#[implement(super::Service)]
195pub(super) async fn respond_to_room(
196	&self,
197	content: RoomMessageEventContent,
198	room_id: &RoomId,
199	user_id: &UserId,
200) -> Result {
201	assert!(self.user_is_admin(user_id).await, "sender is not admin");
202
203	let state_lock = self.services.state.mutex.lock(room_id).await;
204
205	if let Err(e) = self
206		.services
207		.timeline
208		.build_and_append_pdu(PduBuilder::timeline(&content), user_id, room_id, &state_lock)
209		.await
210	{
211		self.handle_response_error(e, room_id, user_id, &state_lock)
212			.boxed() // cold arm
213			.await
214			.unwrap_or_else(default_log);
215	}
216
217	Ok(())
218}
219
220#[implement(super::Service)]
221async fn handle_response_error(
222	&self,
223	e: Error,
224	room_id: &RoomId,
225	user_id: &UserId,
226	state_lock: &RoomMutexGuard,
227) -> Result {
228	error!(%e, "Failed to build and append admin room response PDU");
229	let content = RoomMessageEventContent::text_plain(format!(
230		"Failed to build and append admin room PDU: \"{e}\"\n\nThe original admin command may \
231		 have finished successfully, but we could not return the output."
232	));
233
234	self.services
235		.timeline
236		.build_and_append_pdu(PduBuilder::timeline(&content), user_id, room_id, state_lock)
237		.boxed() // size firewall
238		.await?;
239
240	Ok(())
241}
242
243/// The thread root of the command event when it was itself sent inside a
244/// thread, so the output joins that thread rather than starting a new relation.
245fn command_thread(pdu: &impl Event) -> Option<OwnedEventId> {
246	pdu.get_content()
247		.ok()
248		.and_then(|content: ExtractRelatesTo| match content.relates_to {
249			| EncryptedRelation::Thread(thread) => Some(thread.event_id),
250			| _ => None,
251		})
252}
253
254fn fits_segment(text: &str, markdown: bool) -> bool {
255	serialized_len(&notice(text, markdown)).is_ok_and(|len| len <= SEGMENT_BUDGET)
256}
257
258impl Mode {
259	/// The relation for the next event: a thread child of the root, or a reply
260	/// to the previous segment when there is one, else to the command.
261	fn relation(&self, previous: Option<&EventId>) -> MessageRelation {
262		match self {
263			| Self::Thread(root) => thread_relation(root),
264			| Self::Reply(command) => reply_relation(previous.unwrap_or(command)),
265		}
266	}
267}
268
269fn notice(text: &str, markdown: bool) -> RoomMessageEventContent {
270	match markdown {
271		| true => notice_markdown(text),
272		| false => RoomMessageEventContent::notice_plain(text),
273	}
274}
275
276fn thread_relation(root: &EventId) -> MessageRelation {
277	Relation::Thread(Thread::without_fallback(root.to_owned()))
278}
279
280fn reply_relation(event_id: &EventId) -> MessageRelation {
281	Relation::Reply(ReplyRelation {
282		in_reply_to: InReplyTo { event_id: event_id.to_owned() },
283	})
284}
285
286#[cfg(test)]
287mod tests {
288	use ruma::{EventId, ID_MAX_BYTES};
289
290	use super::{RELATION_RESERVE, notice, reply_relation, thread_relation};
291
292	/// The reserve must cover the largest relation (a maximum-length event id),
293	/// so a segment measured without its relation still fits once attached.
294	#[test]
295	fn relation_reserve_covers_max_length_event_id() {
296		let raw = format!("${}", "a".repeat(ID_MAX_BYTES.saturating_sub(1)));
297		let event_id = <&EventId>::try_from(raw.as_str()).expect("valid max-length event id");
298		let bare = serde_json::to_string(&notice("body", true))
299			.expect("serialize")
300			.len();
301
302		for relation in [reply_relation(event_id), thread_relation(event_id)] {
303			let mut content = notice("body", true);
304			content.relates_to = Some(relation);
305
306			let full = serde_json::to_string(&content)
307				.expect("serialize")
308				.len();
309
310			assert!(full.saturating_sub(bare) <= RELATION_RESERVE);
311		}
312	}
313}