Skip to main content

tuwunel_service/admin/
mod.rs

1mod attach;
2pub mod console;
3pub mod context;
4pub mod create;
5mod execute;
6mod grant;
7mod notices;
8mod processor;
9mod register;
10mod respond;
11#[cfg(test)]
12mod tests;
13
14use std::{
15	collections::BTreeMap,
16	sync::{Arc, Mutex as StdMutex, RwLock as StdRwLock},
17	time::Instant,
18};
19
20use async_trait::async_trait;
21pub use context::Context;
22pub use create::create_admin_room;
23use futures::TryFutureExt;
24use ruma::{
25	OwnedEventId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, RoomId, RoomOrAliasId, UserId,
26};
27use tokio::sync::mpsc::{Receiver, Sender, channel};
28use tuwunel_core::{
29	Err, Result, debug, err, error::default_log, implement, utils::ReadyExt, warn,
30};
31use tuwunel_matrix::{Event, event::MsgType};
32
33use crate::rooms::state::RoomMutexGuard;
34
35pub struct Service {
36	services: Arc<crate::services::OnceServices>,
37	queue: StdRwLock<Queue>,
38	pub command: StdRwLock<Option<Arc<dyn Command>>>,
39	pub admin_alias: OwnedRoomAliasId,
40	register_nonces: StdMutex<BTreeMap<String, Instant>>,
41	#[cfg(feature = "console")]
42	pub console: Arc<console::Console>,
43}
44
45/// State of the command queue's sending half.
46///
47/// Every worker start opens a fresh queue, so a worker restarted after a panic
48/// replaces the dead one. An interrupt closes it for good, and a worker first
49/// polled after that exits rather than open a queue nothing would close.
50enum Queue {
51	/// No worker has opened the queue yet.
52	Pending,
53
54	/// Commands sent here reach the running worker.
55	Open(Sender<CommandInput>),
56
57	/// Interrupted; no worker reopens the queue.
58	Closed,
59}
60
61/// Inputs to a command: its multi-line text, the event to reply to, and who
62/// sent it.
63///
64/// An input without a sender is the operator's, from the console or the
65/// `admin.execute` and `admin.signal_execute` lists; converting a bare command
66/// string builds one.
67#[derive(Clone, Debug, Default)]
68pub struct CommandInput {
69	/// The command line, followed by any body lines.
70	pub command: String,
71
72	/// The event the command's response replies to.
73	pub reply_id: Option<OwnedEventId>,
74
75	/// The user who sent the command, or `None` for the operator.
76	pub sender: Option<OwnedUserId>,
77}
78
79/// Root of a clap command tree installed by a downstream crate.
80#[async_trait]
81pub trait Command: Send + Sync + 'static {
82	/// The clap command tree; equivalent to
83	/// `<C as clap::CommandFactory>::command()`.
84	fn clap(&self) -> clap::Command;
85
86	/// Dispatch already-parsed argument matches to the matching handler.
87	async fn dispatch(&self, matches: clap::ArgMatches, context: &Context<'_>) -> Result;
88}
89
90/// Carries a rendered command outcome while preserving its status.
91///
92/// `Ok(Some(output))` reports success, `Err(output)` reports failure, and
93/// `Ok(None)` suppresses the response. Callers do not infer status from text.
94pub type ProcessorResult = Result<Option<CommandOutput>, CommandOutput>;
95
96/// Textual output of a completed command. Markdown is the norm; Plain carries
97/// clap usage and error text, which must never be markdown-rendered.
98pub enum CommandOutput {
99	Markdown(String),
100	Plain(String),
101}
102
103impl From<String> for CommandInput {
104	fn from(command: String) -> Self { Self { command, ..Default::default() } }
105}
106
107impl From<&str> for CommandInput {
108	fn from(command: &str) -> Self { command.to_owned().into() }
109}
110
111impl CommandOutput {
112	#[inline]
113	#[must_use]
114	pub fn as_str(&self) -> &str {
115		match self {
116			| Self::Markdown(text) | Self::Plain(text) => text,
117		}
118	}
119}
120
121/// Maximum number of commands which can be queued for dispatch.
122const COMMAND_QUEUE_LIMIT: usize = 512;
123
124#[async_trait]
125impl crate::Service for Service {
126	fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
127		Ok(Arc::new(Self {
128			services: args.services.clone(),
129			queue: StdRwLock::new(Queue::Pending),
130			command: StdRwLock::new(None),
131			admin_alias: OwnedRoomAliasId::try_from(format!("#admins:{}", args.server.name))
132				.expect("#admins:server_name is valid alias name"),
133			register_nonces: StdMutex::new(BTreeMap::new()),
134			#[cfg(feature = "console")]
135			console: console::Console::new(args),
136		}))
137	}
138
139	async fn worker(self: Arc<Self>) -> Result {
140		let mut signals = self.services.server.signal.subscribe();
141		let Some(mut receiver) = self
142			.queue
143			.write()
144			.expect("locked for writing")
145			.open()
146		else {
147			return Ok(());
148		};
149
150		self.console_auto_start().await;
151
152		loop {
153			tokio::select! {
154				command = receiver.recv() => match command {
155					Some(command) => self.handle_command(command).await,
156					None => break,
157				},
158				sig = signals.recv() => if let Ok(sig) = sig {
159					self.handle_signal(sig).await;
160				},
161			}
162		}
163
164		//TODO: not unwind safe
165		self.interrupt().await;
166		self.console_auto_stop().await;
167
168		Ok(())
169	}
170
171	async fn interrupt(&self) {
172		#[cfg(feature = "console")]
173		self.console.interrupt();
174
175		*self.queue.write().expect("locked for writing") = Queue::Closed;
176	}
177
178	fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
179}
180
181/// Opens a fresh queue for a starting worker unless an interrupt closed it
182/// first.
183///
184/// Returns the receiving half, or `None` when the worker should exit.
185#[implement(Queue)]
186fn open(&mut self) -> Option<Receiver<CommandInput>> {
187	match self {
188		| Self::Closed => None,
189		| Self::Pending | Self::Open(_) => {
190			let (sender, receiver) = channel(COMMAND_QUEUE_LIMIT);
191
192			*self = Self::Open(sender);
193			Some(receiver)
194		},
195	}
196}
197
198impl Service {
199	/// Queues a command for the service worker and returns once it is queued.
200	///
201	/// The worker processes it later and replies to the `reply_id` event in its
202	/// room, posting nothing without one. Queueing waits while the queue is
203	/// full, and errors when the queue is unavailable or closed.
204	pub async fn command(&self, input: CommandInput) -> Result {
205		let Some(queue) = self
206			.queue
207			.read()
208			.expect("locked for reading")
209			.sender()
210		else {
211			return Err!("Admin command queue unavailable.");
212		};
213
214		queue
215			.send(input)
216			.map_err(|e| err!("Failed to enqueue admin command: {e:?}"))
217			.await
218	}
219
220	/// Dispatches a command to the processor on the current task and waits for
221	/// completion.
222	///
223	/// The queue is bypassed, so the outcome returns to the caller rather than
224	/// being posted as a reply.
225	pub async fn command_in_place(&self, input: CommandInput) -> ProcessorResult {
226		self.process_command(&input).await
227	}
228
229	/// Invokes the tab-completer to complete the command. When unavailable,
230	/// None is returned.
231	pub fn complete_command(&self, command: &str) -> Option<String> {
232		self.command
233			.read()
234			.expect("locked for reading")
235			.as_ref()
236			.map(|root| processor::complete(root.clap(), command))
237	}
238
239	async fn handle_signal(&self, sig: &'static str) {
240		if sig == execute::SIGNAL {
241			self.signal_execute().await.ok();
242		}
243
244		#[cfg(feature = "console")]
245		self.console.handle_signal(sig);
246	}
247
248	async fn handle_command(&self, command: CommandInput) {
249		match self.process_command(&command).await {
250			| Ok(None) => debug!("Command successful with no response"),
251			| Err(output) | Ok(Some(output)) => self
252				.handle_response(output, command.reply_id.as_deref())
253				.await
254				.unwrap_or_else(default_log),
255		}
256	}
257
258	async fn process_command(&self, command: &CommandInput) -> ProcessorResult {
259		let root = self
260			.command
261			.read()
262			.expect("locked for reading")
263			.clone()
264			.expect("Admin module is not loaded");
265
266		processor::handle_command(root, Arc::clone(self.services.get()), command).await
267	}
268
269	/// Checks whether a given user is an admin of this server
270	pub async fn user_is_admin(&self, user_id: &UserId) -> bool {
271		if user_id == self.services.globals.server_user {
272			return true;
273		}
274
275		let Ok(admin_room) = self.get_admin_room().await else {
276			return false;
277		};
278
279		self.services
280			.state_cache
281			.is_joined(user_id, &admin_room)
282			.await
283	}
284
285	/// Checks whether a given user is the only active admin left on this server.
286	///
287	/// The server user is never counted: it can sign in only while an emergency
288	/// password is configured. Deactivated accounts still joined to the admin
289	/// room are not counted either, since none of them can sign in to act. Nor
290	/// is a passwordless account, such as an appservice's user, since it stores
291	/// the same empty password as a deactivated one.
292	pub async fn user_is_last_admin(&self, user_id: &UserId) -> bool {
293		let server_user: &UserId = &self.services.globals.server_user;
294		if user_id == server_user {
295			return false;
296		}
297
298		let Ok(admin_room) = self.get_admin_room().await else {
299			return false;
300		};
301
302		if !self
303			.services
304			.state_cache
305			.is_joined(user_id, &admin_room)
306			.await
307		{
308			return false;
309		}
310
311		!self
312			.services
313			.state_cache
314			.active_local_users_in_room(&admin_room)
315			.ready_any(|member| member != user_id && member != server_user)
316			.await
317	}
318
319	/// Gets the room ID of the admin room
320	///
321	/// Errors are propagated from the database, and will have None if there is
322	/// no admin room
323	pub async fn get_admin_room(&self) -> Result<OwnedRoomId> {
324		let room_id = self
325			.services
326			.alias
327			.resolve_local_alias(&self.admin_alias)
328			.await?;
329
330		self.services
331			.state_cache
332			.is_joined(&self.services.globals.server_user, &room_id)
333			.await
334			.then_some(room_id)
335			.ok_or_else(|| err!(Request(NotFound("Admin user not joined to admin room"))))
336	}
337
338	/// Gets the room reports are posted to.
339	///
340	/// Uses the configured report room when set and usable, otherwise the admin room.
341	pub async fn get_report_room(&self) -> Result<OwnedRoomId> {
342		let Some(report_room) = self
343			.services
344			.server
345			.config
346			.admin
347			.report_room
348			.as_ref()
349		else {
350			return self.get_admin_room().await;
351		};
352
353		match self.resolve_report_room(report_room).await {
354			| Ok(room_id) => Ok(room_id),
355			| Err(e) => {
356				warn!(%report_room, error = %e, "Falling back to the admin room for reports");
357				self.get_admin_room().await
358			},
359		}
360	}
361
362	async fn resolve_report_room(&self, report_room: &RoomOrAliasId) -> Result<OwnedRoomId> {
363		let room_id = self
364			.services
365			.alias
366			.maybe_resolve(report_room)
367			.await?;
368
369		self.services
370			.state_cache
371			.is_joined(&self.services.globals.server_user, &room_id)
372			.await
373			.then_some(room_id)
374			.ok_or_else(|| err!("server user is not joined to the configured report room"))
375	}
376
377	/// Returns whether a message event is an admin command to run.
378	///
379	/// Only an `m.text` from an admin qualifies: prefixed with `!admin` or the
380	/// server user's ID in the admin room, or escaped as `\!admin` by a local
381	/// admin anywhere when escape commands are enabled. The server user's own
382	/// messages in the admin room are refused unless the emergency password is
383	/// set.
384	pub async fn is_admin_command<Pdu>(&self, event: &Pdu, body: &str) -> bool
385	where
386		Pdu: Event,
387	{
388		let body = body.trim_start();
389
390		// Server-side command-escape with public echo
391		let is_escape = body.starts_with('\\');
392		let is_public_escape = is_escape
393			&& body
394				.trim_start_matches('\\')
395				.starts_with("!admin");
396
397		// Admin command with public echo (in admin room)
398		let server_user = &self.services.globals.server_user;
399		let is_public_prefix =
400			body.starts_with("!admin") || body.starts_with(server_user.as_str());
401
402		// Expected backward branch
403		if !is_public_escape && !is_public_prefix {
404			return false;
405		}
406
407		let user_is_local = self
408			.services
409			.globals
410			.user_is_local(event.sender());
411
412		// only allow public escaped commands by local admins
413		if is_public_escape && !user_is_local {
414			return false;
415		}
416
417		// Check if server-side command-escape is disabled by configuration
418		if is_public_escape && !self.services.server.config.admin.escape_commands {
419			return false;
420		}
421
422		// Spec: an m.notice must never be answered automatically. Other msgtypes'
423		// bodies are captions, filenames or emotes a forward or repost can carry.
424		if event.msgtype() != Some(MsgType::Text) {
425			return false;
426		}
427
428		// Prevent unescaped !admin from being used outside of the admin room
429		if is_public_prefix && !self.is_admin_room(event.room_id()).await {
430			return false;
431		}
432
433		// Only senders who are admin can proceed
434		if !self.user_is_admin(event.sender()).await {
435			return false;
436		}
437
438		// This will evaluate to false if the emergency password is set up so that
439		// the administrator can execute commands as the server user
440		let emergency_password_set = self
441			.services
442			.server
443			.config
444			.authentication
445			.emergency_password
446			.is_some();
447
448		let from_server = event.sender() == server_user && !emergency_password_set;
449		if from_server && self.is_admin_room(event.room_id()).await {
450			return false;
451		}
452
453		// Authentic admin command
454		true
455	}
456
457	#[must_use]
458	pub async fn is_admin_room(&self, room_id_: &RoomId) -> bool {
459		self.get_admin_room()
460			.map_ok(|room_id| room_id == room_id_)
461			.await
462			.unwrap_or(false)
463	}
464}
465
466#[implement(Queue)]
467#[inline]
468fn sender(&self) -> Option<Sender<CommandInput>> {
469	match self {
470		| Self::Open(sender) => Some(sender.clone()),
471		| Self::Pending | Self::Closed => None,
472	}
473}
474
475/// Locks the admins room's state, when there is an admins room.
476///
477/// Hold the guard from the [`Service::user_is_last_admin`] check until the
478/// change it permits is made. The admins room's leave and ban guard runs under
479/// the same lock, so two concurrent removals cannot each see the other as the
480/// admin who remains.
481#[implement(Service)]
482pub async fn lock_admin_room(&self) -> Option<RoomMutexGuard> {
483	let admin_room = self.get_admin_room().await.ok()?;
484
485	self.services
486		.state
487		.mutex
488		.lock(&admin_room)
489		.await
490		.into()
491}