Skip to main content

tuwunel_service/users/
mod.rs

1mod browser_session;
2mod create;
3mod dehydrated_device;
4pub mod device;
5mod invite_filter;
6mod keys;
7mod ldap;
8mod register;
9mod server_user;
10#[cfg(test)]
11mod tests;
12
13use std::{future::ready, sync::Arc};
14
15use futures::{Stream, StreamExt, TryFutureExt};
16use ruma::{
17	MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, UserId,
18	api::client::filter::FilterDefinition,
19	events::{
20		GlobalAccountDataEventType,
21		ignored_user_list::{IgnoredUserListEvent, IgnoredUserListEventContent},
22	},
23};
24use serde::{Deserialize, Serialize};
25use tuwunel_core::{
26	Err, Result, debug_warn, err, implement, is_equal_to,
27	smallstr::SmallString,
28	trace,
29	utils::{
30		self, BoolExt, MutexMap, ReadyExt, hash::password as hash_password, result::NotFound,
31		stream::TryIgnore,
32	},
33	warn,
34};
35use tuwunel_database::{Deserialized, Json, Map};
36use tuwunel_matrix::pdu::PduCount;
37
38pub type LoginProviderId = SmallString<[u8; 32]>;
39type LoginTokenId = SmallString<[u8; 48]>;
40
41pub use self::{
42	browser_session::BrowserSession,
43	dehydrated_device::DehydratedDevice,
44	invite_filter::InviteFilter,
45	keys::{DeviceListChange, DeviceListRecord, parse_master_key},
46	register::Register,
47	server_user::SERVER_USER_KEY,
48};
49
50pub const PASSWORD_SENTINEL: &str = "*";
51pub const PASSWORD_DISABLED: &str = "";
52
53/// Forensic record for a moderation action (MSC3823 suspend, MSC3939 lock).
54/// Presence of the row is the load-bearing fact; this body is written but
55/// never read on the hot path.
56#[derive(Clone, Debug, Serialize, Deserialize)]
57pub struct Moderation {
58	pub when: MilliSecondsSinceUnixEpoch,
59	pub by: OwnedUserId,
60}
61
62/// An authenticated login-token owner and the provider that authenticated it.
63///
64/// Native and password authentication carry no provider. SSO tokens preserve
65/// the provider verified by the server-side SSO session.
66pub struct LoginToken {
67	/// The local user authenticated by the token.
68	pub user_id: OwnedUserId,
69	/// The SSO provider that authenticated the user, if any.
70	pub idp_id: Option<LoginProviderId>,
71}
72
73pub struct Service {
74	services: Arc<crate::services::OnceServices>,
75	db: Data,
76	device_list_mutex: MutexMap<OwnedUserId, ()>,
77	login_token_mutex: MutexMap<LoginTokenId, ()>,
78	changing_password: MutexMap<OwnedUserId, ()>,
79	// Entries live only while claims for a user/device hold or await the lock.
80	claiming_one_time_keys: MutexMap<(OwnedUserId, OwnedDeviceId), ()>,
81	/// Serializes the writers of one device and of each of a user's key rows.
82	///
83	/// Entries live only while held or awaited: by a device's creation, token
84	/// issuance, metadata update (each presence ping's last-seen) or removal,
85	/// a device key upload, a signature merge, or a cross-signing key write (one
86	/// per key row).
87	updating_device: MutexMap<(OwnedUserId, OwnedDeviceId), ()>,
88}
89
90struct Data {
91	keychangeid_devicechange: Arc<Map>,
92	keychangeid_userid: Arc<Map>,
93	keyid_key: Arc<Map>,
94	onetimekeyid4225_otk: Option<Arc<Map>>,
95	openidtoken_expiresatuserid: Arc<Map>,
96	logintoken_expiresatuserid: Arc<Map>,
97	todeviceid_events: Arc<Map>,
98	spentrefresh_userdeviceid: Arc<Map>,
99	token_userdeviceid: Arc<Map>,
100	userdeviceid_metadata: Arc<Map>,
101	userdeviceid_token: Arc<Map>,
102	userdeviceidtoken_index: Arc<Map>,
103	userdeviceid_refresh: Arc<Map>,
104	userdeviceid_spentrefresh: Arc<Map>,
105	userdeviceidalgorithm_fallback: Arc<Map>,
106	oidcdevice_userdeviceid: Arc<Map>,
107	oidccskeybypass_userid: Arc<Map>,
108	userfilterid_filter: Arc<Map>,
109	userid_dehydrateddevice: Arc<Map>,
110	userid_devicelistversion: Arc<Map>,
111	userid_erased: Arc<Map>,
112	userid_lastonetimekeyupdate: Arc<Map>,
113	userid_locked: Arc<Map>,
114	userid_masterkeyid: Arc<Map>,
115	userid_password: Arc<Map>,
116	userid_origin: Arc<Map>,
117	userid_selfsigningkeyid: Arc<Map>,
118	userid_suspended: Arc<Map>,
119	userid_usersigningkeyid: Arc<Map>,
120	useridbrowsersession_createdat: Arc<Map>,
121}
122
123impl crate::Service for Service {
124	fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
125		Ok(Arc::new(Self {
126			services: args.services.clone(),
127			device_list_mutex: MutexMap::new(),
128			login_token_mutex: MutexMap::new(),
129			changing_password: MutexMap::new(),
130			claiming_one_time_keys: MutexMap::new(),
131			updating_device: MutexMap::new(),
132			db: Data {
133				keychangeid_devicechange: args.db["keychangeid_devicechange"].clone(),
134				keychangeid_userid: args.db["keychangeid_userid"].clone(),
135				keyid_key: args.db["keyid_key"].clone(),
136				onetimekeyid4225_otk: args.db.get("onetimekeyid4225_otk").ok().cloned(),
137				openidtoken_expiresatuserid: args.db["openidtoken_expiresatuserid"].clone(),
138				logintoken_expiresatuserid: args.db["logintoken_expiresatuserid"].clone(),
139				oidcdevice_userdeviceid: args.db["oidcdevice_userdeviceid"].clone(),
140				oidccskeybypass_userid: args.db["oidccskeybypass_userid"].clone(),
141				todeviceid_events: args.db["todeviceid_events"].clone(),
142				spentrefresh_userdeviceid: args.db["spentrefresh_userdeviceid"].clone(),
143				token_userdeviceid: args.db["token_userdeviceid"].clone(),
144				userdeviceid_metadata: args.db["userdeviceid_metadata"].clone(),
145				userdeviceid_token: args.db["userdeviceid_token"].clone(),
146				userdeviceidtoken_index: args.db["userdeviceidtoken_index"].clone(),
147				userdeviceid_refresh: args.db["userdeviceid_refresh"].clone(),
148				userdeviceid_spentrefresh: args.db["userdeviceid_spentrefresh"].clone(),
149				userdeviceidalgorithm_fallback: args.db["userdeviceidalgorithm_fallback"].clone(),
150				userfilterid_filter: args.db["userfilterid_filter"].clone(),
151				userid_dehydrateddevice: args.db["userid_dehydrateddevice"].clone(),
152				userid_devicelistversion: args.db["userid_devicelistversion"].clone(),
153				userid_erased: args.db["userid_erased"].clone(),
154				userid_lastonetimekeyupdate: args.db["userid_lastonetimekeyupdate"].clone(),
155				userid_locked: args.db["userid_locked"].clone(),
156				userid_masterkeyid: args.db["userid_masterkeyid"].clone(),
157				userid_password: args.db["userid_password"].clone(),
158				userid_origin: args.db["userid_origin"].clone(),
159				userid_selfsigningkeyid: args.db["userid_selfsigningkeyid"].clone(),
160				userid_suspended: args.db["userid_suspended"].clone(),
161				userid_usersigningkeyid: args.db["userid_usersigningkeyid"].clone(),
162				useridbrowsersession_createdat: args.db["useridbrowsersession_createdat"].clone(),
163			},
164		}))
165	}
166
167	fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
168}
169
170impl Service {
171	/// Returns true/false based on whether the recipient/receiving user has
172	/// blocked the sender
173	pub async fn user_is_ignored(&self, sender_user: &UserId, recipient_user: &UserId) -> bool {
174		self.ignored_users(recipient_user)
175			.await
176			.is_some_and(|ignored| {
177				ignored
178					.ignored_users
179					.keys()
180					.any(|blocked_user| blocked_user == sender_user)
181			})
182	}
183
184	/// The users a user ignores account-wide.
185	///
186	/// Callers testing one list against many users take this rather than
187	/// [`Self::user_is_ignored`], which re-reads the list per test.
188	pub async fn ignored_users(&self, user_id: &UserId) -> Option<IgnoredUserListEventContent> {
189		self.services
190			.account_data
191			.get_global(user_id, GlobalAccountDataEventType::IgnoredUserList)
192			.await
193			.map(|ignored: IgnoredUserListEvent| ignored.content)
194			.ok()
195	}
196
197	/// Create a new user account on this homeserver.
198	///
199	/// User origin is by default "password" (meaning that it will login using
200	/// its user_id/password). Users with other origins (currently only "ldap"
201	/// is available) have special login processes.
202	#[inline]
203	pub async fn create(
204		&self,
205		user_id: &UserId,
206		password: Option<&str>,
207		origin: Option<&str>,
208	) -> Result {
209		let _password_guard = self.changing_password.lock(user_id).await;
210
211		self.check_creation(user_id).await?;
212
213		let origin = origin.unwrap_or("password");
214
215		if password.is_none() {
216			self.create_disabled(user_id, origin);
217			return Ok(());
218		}
219
220		self.db.userid_origin.insert(user_id, origin);
221		self.set_password_locked(user_id, password).await
222	}
223
224	/// Refuses a local user ID that once joined the admin room but has no account.
225	///
226	/// Refusals return `M_USER_IN_USE` and log the user ID without changing account
227	/// or membership state. Existing accounts and the server user remain eligible.
228	pub async fn check_creation(&self, user_id: &UserId) -> Result {
229		if self.services.globals.user_is_local(user_id)
230			&& user_id != self.services.globals.server_user
231			&& let Some(admin_room) = self
232				.services
233				.alias
234				.resolve_local_alias(&self.services.admin.admin_alias)
235				.await
236				.optional()?
237			&& self
238				.services
239				.state_cache
240				.once_joined(user_id, &admin_room)
241				.await
242			&& !self.exists(user_id).await
243		{
244			warn!(%user_id, "Refusing a name previously joined to the admin room");
245			return Err!(Request(UserInUse("User ID is not available.")));
246		}
247
248		Ok(())
249	}
250
251	/// Deactivate account
252	pub async fn deactivate_account(&self, user_id: &UserId) -> Result {
253		// Held until the password is cleared; see `lock_admin_room`.
254		let admin_lock = self.services.admin.lock_admin_room().await;
255
256		// Nobody would be left to reactivate this account or any other. Every
257		// deactivation path reaches here first, while the admins room refuses the
258		// last admin's departure only after the account is already deactivated.
259		if self
260			.services
261			.admin
262			.user_is_last_admin(user_id)
263			.await
264		{
265			return Err!(Request(Forbidden(
266				"Cannot deactivate the last admin of this server. Make another user an admin \
267				 first."
268			)));
269		}
270
271		// The one step here that can fail, so before anything irreversible.
272		self.end_browser_sessions(user_id).await?;
273		self.remove_devices(user_id, None).await;
274
275		// Set the password to "" to indicate a deactivated account. Hashes will never
276		// result in an empty string, so the user will not be able to log in again.
277		// Systems like changing the password without logging in should check if the
278		// account is deactivated.
279		self.set_password(user_id, None).await?;
280		drop(admin_lock);
281
282		self.services
283			.delayed_events
284			.remove_user(user_id)
285			.await;
286
287		// Revoke any SSO authorizations, outside the lock since each is a request
288		// to the identity provider.
289		self.services
290			.oauth
291			.revoke_user_tokens(user_id)
292			.await;
293
294		// TODO: Unhook 3PID
295		Ok(())
296	}
297
298	/// Check if a user has an account on this homeserver.
299	#[inline]
300	pub async fn exists(&self, user_id: &UserId) -> bool {
301		self.db.userid_password.get(user_id).await.is_ok()
302	}
303
304	/// Check if account is deactivated
305	pub async fn is_deactivated(&self, user_id: &UserId) -> Result<bool> {
306		self.db
307			.userid_password
308			.get(user_id)
309			.map_ok(|val| val.is_empty())
310			.map_err(|_| err!(Request(NotFound("User does not exist."))))
311			.await
312	}
313
314	/// Check if account is active, infallible
315	pub async fn is_active(&self, user_id: &UserId) -> bool {
316		!self.is_deactivated(user_id).await.unwrap_or(true)
317	}
318
319	/// Check if account is active, infallible
320	pub async fn is_active_local(&self, user_id: &UserId) -> bool {
321		self.services.globals.user_is_local(user_id) && self.is_active(user_id).await
322	}
323
324	/// Whether the account is a guest; a missing or unreadable one is not.
325	///
326	/// Guests share the empty password marker with the passwordless users an
327	/// appservice registers. A user in an appservice's exclusive namespace, or
328	/// the appservice's own sender, belongs to that appservice and is never a
329	/// guest, whatever token it acts with.
330	pub async fn is_guest(&self, user_id: &UserId) -> bool {
331		self.is_deactivated(user_id)
332			.await
333			.unwrap_or(false)
334			&& self
335				.services
336				.appservice
337				.is_exclusive_user_id(user_id)
338				.await
339				.is_false()
340	}
341
342	/// Gate an LDAP-authenticated login into an existing local account.
343	///
344	/// Only a deactivated account is rejected. A password-origin account
345	/// passes, since a successful bind establishes the caller's identity
346	/// however their account was created, and a localpart with no local
347	/// account passes on its way to registration.
348	pub async fn check_ldap_login(&self, user_id: &UserId) -> Result {
349		self.deactivated_check(user_id).await
350	}
351
352	/// Reject a deactivated account with 403 `M_USER_DEACTIVATED`.
353	///
354	/// An account that does not exist is not deactivated, as in Synapse. One
355	/// created without a password, as an appservice's users often are, reads
356	/// as deactivated, since both store an empty password.
357	pub async fn deactivated_check(&self, user_id: &UserId) -> Result {
358		self.db
359			.userid_password
360			.get(user_id)
361			.map_ok(|password| password.is_empty())
362			.await
363			.optional()?
364			.unwrap_or_default()
365			.is_false()
366			.into_option()
367			.ok_or_else(|| err!(Request(UserDeactivated("This user has been deactivated."))))
368	}
369
370	/// MSC3823: account is suspended (read-mostly mode, sessions retained).
371	pub async fn is_suspended(&self, user_id: &UserId) -> bool {
372		self.db
373			.userid_suspended
374			.get(user_id)
375			.await
376			.is_ok()
377	}
378
379	/// MSC3939: reject a request from a locked account.
380	///
381	/// The rejection maps to 401 `M_USER_LOCKED` with `soft_logout: true`, so
382	/// the client retains its session and polls for the unlock. The login and
383	/// refresh routes and the request middleware share this gate.
384	pub async fn locked_check(&self, user_id: &UserId) -> Result {
385		self.is_locked(user_id)
386			.await
387			.is_false()
388			.ok_or_else(|| err!(Request(UserLocked("This account has been locked."))))
389	}
390
391	/// MSC3939: account is locked (401 + soft_logout, sessions retained).
392	///
393	/// The row's presence is the entire state, and locking never invalidates
394	/// access tokens, so clearing the row restores every session intact.
395	/// Both `locked_check` and the admin lock surfaces read it.
396	pub async fn is_locked(&self, user_id: &UserId) -> bool {
397		self.db.userid_locked.get(user_id).await.is_ok()
398	}
399
400	/// MSC4025: the user's events serve as pruned copies to recipients not
401	/// joined at the event. Presence-only for the serving gate.
402	pub async fn is_erased(&self, user_id: &UserId) -> bool {
403		self.db.userid_erased.get(user_id).await.is_ok()
404	}
405
406	/// MSC4025: the global count recorded at erasure, for admin surfacing;
407	/// the serving gate never reads it.
408	pub async fn erasure_count(&self, user_id: &UserId) -> Option<PduCount> {
409		self.db
410			.userid_erased
411			.get(user_id)
412			.await
413			.deserialized()
414			.map(PduCount::from_unsigned)
415			.ok()
416	}
417
418	/// MSC3823: forensic record for the active suspension, if any.
419	pub async fn get_suspension(&self, user_id: &UserId) -> Option<Moderation> {
420		self.db
421			.userid_suspended
422			.get(user_id)
423			.await
424			.deserialized::<Json<_>>()
425			.map(|Json(m)| m)
426			.ok()
427	}
428
429	/// MSC3939: forensic record for the active lock, if any.
430	pub async fn get_lock(&self, user_id: &UserId) -> Option<Moderation> {
431		self.db
432			.userid_locked
433			.get(user_id)
434			.await
435			.deserialized::<Json<_>>()
436			.map(|Json(m)| m)
437			.ok()
438	}
439
440	pub fn set_suspended(&self, user_id: &UserId, by: &UserId) {
441		let entry = Moderation {
442			when: MilliSecondsSinceUnixEpoch::now(),
443			by: by.to_owned(),
444		};
445
446		self.db
447			.userid_suspended
448			.raw_put(user_id, Json(entry));
449	}
450
451	pub fn clear_suspended(&self, user_id: &UserId) { self.db.userid_suspended.remove(user_id); }
452
453	/// MSC4025: mark the user erased, recording the current global count.
454	pub fn set_erased(&self, user_id: &UserId) {
455		let count = self.services.globals.current_count();
456
457		self.db.userid_erased.raw_put(user_id, count);
458	}
459
460	/// MSC4025: erasure is reversible; clearing the marker restores the
461	/// unredacted view.
462	pub fn clear_erased(&self, user_id: &UserId) { self.db.userid_erased.remove(user_id); }
463
464	pub fn set_locked(&self, user_id: &UserId, by: &UserId) {
465		let entry = Moderation {
466			when: MilliSecondsSinceUnixEpoch::now(),
467			by: by.to_owned(),
468		};
469
470		self.db
471			.userid_locked
472			.raw_put(user_id, Json(entry));
473	}
474
475	pub fn clear_locked(&self, user_id: &UserId) { self.db.userid_locked.remove(user_id); }
476
477	/// Returns the number of users registered on this server.
478	#[inline]
479	pub async fn count(&self) -> usize { self.db.userid_password.count().await }
480
481	/// Returns whether the user table contains no accounts.
482	///
483	/// The lookup stops after the first account and propagates storage errors.
484	#[tracing::instrument(level = "trace", skip_all)]
485	pub async fn is_empty(&self) -> Result<bool> {
486		self.db
487			.userid_password
488			.keys()
489			.take(1)
490			.ready_fold(Ok(true), |_, user: Result<&UserId>| user.map(|_| false))
491			.await
492	}
493
494	/// Returns an iterator over all users on this homeserver.
495	pub fn stream(&self) -> impl Stream<Item = &UserId> + Send {
496		self.db.userid_password.keys().ignore_err()
497	}
498
499	/// Returns a list of local users as list of usernames.
500	///
501	/// A user account is considered `local` if the length of it's password is
502	/// greater then zero.
503	pub fn list_local_users(&self) -> impl Stream<Item = &UserId> + Send + '_ {
504		self.db
505			.userid_password
506			.stream()
507			.ignore_err()
508			.ready_filter_map(|(u, p): (&UserId, &[u8])| (!p.is_empty()).then_some(u))
509	}
510
511	/// Returns the origin of the user (password/LDAP/...).
512	pub async fn origin(&self, user_id: &UserId) -> Result<String> {
513		self.db
514			.userid_origin
515			.get(user_id)
516			.await
517			.deserialized()
518	}
519
520	/// Returns whether the user has a password. Disabled accounts and
521	/// registrations setting a sentinel password will return false here.
522	pub async fn has_password(&self, user_id: &UserId) -> Result<bool> {
523		self.password_hash(user_id)
524			.map_ok(|value| is_password_hash(&value))
525			.await
526	}
527
528	/// Returns the password hash for the given user.
529	pub async fn password_hash(&self, user_id: &UserId) -> Result<String> {
530		self.db
531			.userid_password
532			.get(user_id)
533			.await
534			.deserialized()
535	}
536
537	/// Hashes and stores the user's password.
538	///
539	/// A real password is hashed at the configured Argon2id cost and marks the
540	/// account as password-origin. `None` stores the disabled marker and the
541	/// sentinel is stored verbatim; neither is hashed. Changing the password of
542	/// an account whose origin is neither password nor SSO is rejected. Setting
543	/// a password or the sentinel first ends the user's browser sessions, and
544	/// failing to end them fails the call; disabling leaves them to be refused
545	/// at use.
546	pub async fn set_password(&self, user_id: &UserId, password: Option<&str>) -> Result {
547		let _password_guard = self.changing_password.lock(user_id).await;
548
549		self.set_password_locked(user_id, password).await
550	}
551
552	/// Changes the password only while the account is active.
553	///
554	/// The active-state check and password write are serialized with account
555	/// deactivation for this user.
556	pub async fn set_password_if_active(
557		&self,
558		user_id: &UserId,
559		password: Option<&str>,
560	) -> Result {
561		self.set_password_if_active_after(user_id, password, ready(()))
562			.await
563	}
564
565	/// Creates a new sync filter. Returns the filter id.
566	#[must_use]
567	pub fn create_filter(&self, user_id: &UserId, filter: &FilterDefinition) -> String {
568		let filter_id = utils::random_string(4);
569
570		let key = (user_id, &filter_id);
571		self.db.userfilterid_filter.put(key, Json(filter));
572
573		filter_id
574	}
575
576	pub async fn get_filter(
577		&self,
578		user_id: &UserId,
579		filter_id: &str,
580	) -> Result<FilterDefinition> {
581		let key = (user_id, filter_id);
582		self.db
583			.userfilterid_filter
584			.qry(&key)
585			.await
586			.deserialized()
587	}
588
589	/// Creates an OpenID token, which can be used to prove that a user has
590	/// access to an account (primarily for integrations)
591	pub fn create_openid_token(&self, user_id: &UserId, token: &str) -> Result<u64> {
592		use std::num::Saturating as Sat;
593
594		let expires_in = self
595			.services
596			.server
597			.config
598			.authentication
599			.openid_token_ttl;
600
601		let expires_at = Sat(utils::millis_since_unix_epoch()) + Sat(expires_in) * Sat(1000);
602
603		let mut value = expires_at.0.to_be_bytes().to_vec();
604		value.extend_from_slice(user_id.as_bytes());
605
606		self.db
607			.openidtoken_expiresatuserid
608			.insert(token.as_bytes(), value.as_slice());
609
610		Ok(expires_in)
611	}
612
613	/// Find out which user an OpenID access token belongs to.
614	pub async fn find_from_openid_token(&self, token: &str) -> Result<OwnedUserId> {
615		let Ok(value) = self
616			.db
617			.openidtoken_expiresatuserid
618			.get(token)
619			.await
620		else {
621			return Err!(Request(Unauthorized("OpenID token is unrecognised")));
622		};
623
624		let (expires_at_bytes, user_bytes) = value.split_at(0_u64.to_be_bytes().len());
625		let expires_at =
626			u64::from_be_bytes(expires_at_bytes.try_into().map_err(|e| {
627				err!(Database("expires_at in openid_userid is invalid u64. {e}"))
628			})?);
629
630		if expires_at < utils::millis_since_unix_epoch() {
631			debug_warn!("OpenID token is expired, removing");
632			self.db
633				.openidtoken_expiresatuserid
634				.remove(token.as_bytes());
635
636			return Err!(Request(Unauthorized("OpenID token is expired")));
637		}
638
639		let user_string = utils::string_from_bytes(user_bytes)
640			.map_err(|e| err!(Database("User ID in openid_userid is invalid unicode. {e}")))?;
641
642		OwnedUserId::try_from(user_string)
643			.map_err(|e| err!(Database("User ID in openid_userid is invalid. {e}")))
644	}
645
646	/// Creates a short-lived login token, which can be used to log in using the
647	/// `m.login.token` mechanism.
648	#[must_use]
649	pub fn create_login_token(&self, user_id: &UserId, token: &str) -> u64 {
650		self.create_login_token_with_provider(user_id, token, None)
651	}
652
653	/// Creates a short-lived login token carrying authenticated SSO provenance.
654	///
655	/// Native authentication passes no provider. SSO callers preserve the
656	/// provider selected in the server-side SSO session.
657	#[must_use]
658	pub fn create_login_token_with_provider(
659		&self,
660		user_id: &UserId,
661		token: &str,
662		idp_id: Option<&str>,
663	) -> u64 {
664		use std::num::Saturating as Sat;
665
666		let expires_in = self
667			.services
668			.server
669			.config
670			.authentication
671			.login
672			.token_ttl;
673
674		let expires_at = Sat(utils::millis_since_unix_epoch()) + Sat(expires_in);
675
676		// A trailing Option is additive under the workspace KV codec evolution rule.
677		let value = (expires_at.0, user_id, idp_id);
678		self.db
679			.logintoken_expiresatuserid
680			.raw_put(token, value);
681
682		expires_in
683	}
684
685	/// Verify a login token is valid and return its owner without consuming it.
686	/// Unlike `find_from_login_token`, the token remains in the database
687	/// after this call and can still be consumed later.
688	pub async fn peek_login_token(&self, token: &str) -> Result<OwnedUserId> {
689		self.peek_login_token_with_provider(token)
690			.map_ok(|login| login.user_id)
691			.await
692	}
693
694	/// Verify a login token and its provider without consuming it.
695	///
696	/// The token remains available for the later consent submission.
697	pub async fn peek_login_token_with_provider(&self, token: &str) -> Result<LoginToken> {
698		let Ok(value) = self
699			.db
700			.logintoken_expiresatuserid
701			.get(token)
702			.await
703		else {
704			return Err!(Request(Forbidden("Login token is unrecognised")));
705		};
706
707		let (expires_at, user_id, idp_id): (u64, OwnedUserId, Option<LoginProviderId>) =
708			value.deserialized()?;
709
710		if expires_at < utils::millis_since_unix_epoch() {
711			trace!(?user_id, ?token, "Removing expired login token");
712			self.db.logintoken_expiresatuserid.remove(token);
713			return Err!(Request(Forbidden("Login token is expired")));
714		}
715
716		Ok(LoginToken { user_id, idp_id })
717	}
718
719	/// Find out which user a login token belongs to.
720	/// Removes the token to prevent double-use attacks.
721	pub async fn find_from_login_token(&self, token: &str) -> Result<OwnedUserId> {
722		self.find_login_token_with_provider(token)
723			.map_ok(|login| login.user_id)
724			.await
725	}
726
727	/// Consume a login token and return its owner and authenticated provider.
728	///
729	/// The token is removed before its authenticated identity is returned.
730	pub async fn find_login_token_with_provider(&self, token: &str) -> Result<LoginToken> {
731		let token_id: LoginTokenId = token.into();
732		let _lock = self.login_token_mutex.lock(&token_id).await;
733
734		let Ok(value) = self
735			.db
736			.logintoken_expiresatuserid
737			.get(token)
738			.await
739		else {
740			return Err!(Request(Forbidden("Login token is unrecognised")));
741		};
742
743		let (expires_at, user_id, idp_id): (u64, OwnedUserId, Option<LoginProviderId>) =
744			value.deserialized()?;
745
746		if expires_at < utils::millis_since_unix_epoch() {
747			trace!(?user_id, ?token, "Removing expired login token");
748
749			self.db.logintoken_expiresatuserid.remove(token);
750
751			return Err!(Request(Forbidden("Login token is expired")));
752		}
753
754		self.db.logintoken_expiresatuserid.remove(token);
755
756		Ok(LoginToken { user_id, idp_id })
757	}
758
759	#[cfg(not(feature = "ldap"))]
760	#[expect(clippy::unused_async)]
761	pub async fn search_ldap(&self, _user_id: &UserId) -> Result<Vec<(String, bool)>> {
762		Err!(FeatureDisabled("ldap"))
763	}
764
765	#[cfg(not(feature = "ldap"))]
766	#[expect(clippy::unused_async)]
767	pub async fn auth_ldap(&self, _user_dn: &str, _password: &str) -> Result {
768		Err!(FeatureDisabled("ldap"))
769	}
770
771	#[cfg(not(feature = "ldap"))]
772	#[must_use]
773	pub fn ldap_bind_dn(&self, _localpart: &str) -> Option<String> { None }
774}
775
776#[implement(Service)]
777async fn set_password_if_active_after(
778	&self,
779	user_id: &UserId,
780	password: Option<&str>,
781	after_check: impl Future<Output = ()>,
782) -> Result {
783	let _password_guard = self.changing_password.lock(user_id).await;
784
785	self.deactivated_check(user_id).await?;
786	after_check.await;
787	self.set_password_locked(user_id, password).await
788}
789
790#[implement(Service)]
791async fn set_password_locked(&self, user_id: &UserId, password: Option<&str>) -> Result {
792	// Non-password origins may only be disabled or assigned the active sentinel.
793	let allowed_origins = ["password", "sso"];
794
795	if password.is_some() && password != Some(PASSWORD_SENTINEL) {
796		let origin = self.origin(user_id).await;
797		let origin = origin.as_deref().unwrap_or("password");
798
799		if !allowed_origins.iter().any(is_equal_to!(&origin)) {
800			return Err!(Request(InvalidParam("Cannot change password of an {origin:?} user.")));
801		}
802	}
803
804	// Before the write, so a failure leaves the old password for a retry. Disabling
805	// needs none: a deactivated account's sessions are refused at use.
806	if password.is_some() {
807		self.end_browser_sessions(user_id).await?;
808	}
809
810	match password {
811		| None => {
812			self.db
813				.userid_password
814				.insert(user_id, PASSWORD_DISABLED);
815		},
816		| Some(PASSWORD_SENTINEL) => {
817			self.db
818				.userid_password
819				.insert(user_id, PASSWORD_SENTINEL);
820		},
821		| Some(password) => {
822			let cost = self.services.config.password_hash_cost();
823			let hash = hash_password(password, cost).map_err(|e| {
824				err!(Request(InvalidParam("Password does not meet the requirements: {e}")))
825			})?;
826
827			self.db.userid_password.insert(user_id, hash);
828			self.db.userid_origin.insert(user_id, "password");
829		},
830	}
831
832	Ok(())
833}
834
835/// Whether a stored password value is a real hash rather than a marker.
836///
837/// The disabled marker and the sentinel hold no password to check against.
838#[must_use]
839pub fn is_password_hash(value: &str) -> bool {
840	value != PASSWORD_DISABLED && value != PASSWORD_SENTINEL
841}