Skip to main content

tuwunel_service/emergency/
mod.rs

1use std::sync::Arc;
2
3use async_trait::async_trait;
4use ruma::{
5	events::{
6		GlobalAccountDataEvent, GlobalAccountDataEventType, push_rules::PushRulesEventContent,
7	},
8	push::Ruleset,
9};
10use serde_json::to_value;
11use tuwunel_core::{Result, debug_warn, error, implement, warn};
12
13pub struct Service {
14	services: Arc<crate::services::OnceServices>,
15}
16
17#[async_trait]
18impl crate::Service for Service {
19	fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
20		Ok(Arc::new(Self { services: args.services.clone() }))
21	}
22
23	async fn worker(self: Arc<Self>) -> Result {
24		let password = self
25			.services
26			.config
27			.authentication
28			.emergency_password
29			.as_deref()
30			.filter(|password| !password.is_empty());
31
32		// Once the option is removed, the server user must be signed out again. That
33		// only has work to do while a password from an earlier start remains.
34		if password.is_none() && !self.emergency_access_remains().await {
35			return Ok(());
36		}
37
38		if self.services.globals.is_read_only() {
39			debug_warn!("emergency password feature ignored in read_only mode.");
40			return Ok(());
41		}
42
43		if password.is_some() && self.services.config.ldap.enable {
44			warn!("emergency password feature not available with LDAP enabled.");
45			return Ok(());
46		}
47
48		self.set_emergency_access(password)
49			.await
50			.inspect_err(|e| error!(%e, "Failed to update emergency access for the server user"))
51	}
52
53	fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
54}
55
56/// Whether the server user still holds a password.
57///
58/// Only an earlier start with `authentication.emergency_password` set gives it one.
59#[implement(Service)]
60async fn emergency_access_remains(&self) -> bool {
61	self.services
62		.users
63		.has_password(&self.services.globals.server_user)
64		.await
65		.unwrap_or(false)
66}
67
68/// Sets or removes the server user's emergency access.
69///
70/// A given password is set along with the default push rules. Without one, the
71/// push rules are cleared and the account is signed out and deactivated.
72#[implement(Service)]
73#[tracing::instrument(level = "debug", skip_all)]
74async fn set_emergency_access(&self, password: Option<&str>) -> Result {
75	let server_user = &self.services.globals.server_user;
76
77	// The password marks the account for cleanup on a later start, so on
78	// removal only `deactivate_account`, the last step, clears it.
79	if password.is_some() {
80		self.services
81			.users
82			.set_password(server_user, password)
83			.await?;
84	}
85
86	let ruleset = password.map_or_else(Ruleset::new, |_| Ruleset::server_default(server_user));
87	let event_type = GlobalAccountDataEventType::PushRules
88		.to_string()
89		.into();
90
91	let content = to_value(&GlobalAccountDataEvent {
92		content: PushRulesEventContent { global: ruleset },
93	})
94	.expect("to json value always works");
95
96	self.services
97		.account_data
98		.update(None, server_user, event_type, &content)
99		.await?;
100
101	if password.is_some() {
102		warn!(
103			"The server account emergency password is set! Please unset it as soon as you \
104			 finish admin account recovery! You will be logged out of the server service \
105			 account when you finish."
106		);
107
108		return Ok(());
109	}
110
111	// Before the password is cleared, so an interrupted revocation retries next start.
112	self.services
113		.oauth
114		.revoke_user_tokens(server_user)
115		.await;
116
117	// Never refused: the last-admin check does not count the server user.
118	self.services
119		.users
120		.deactivate_account(server_user)
121		.await
122}