Skip to main content

tuwunel_service/uiaa/
mod.rs

1use std::{
2	net::IpAddr,
3	ops::ControlFlow,
4	sync::{Arc, Mutex},
5};
6
7use futures::{TryStreamExt, pin_mut};
8use lru_cache::LruCache;
9use ruma::{
10	CanonicalJsonValue, DeviceId, OwnedDeviceId, OwnedUserId, UserId,
11	api::{
12		client::uiaa::{
13			AuthData, AuthType, EmailIdentity, Password, ThirdpartyIdCredentials, UiaaInfo,
14			UserIdentifier,
15		},
16		error::{ErrorKind, StandardErrorBody},
17	},
18};
19use tuwunel_core::{
20	Err, Result, err, error, extract, implement,
21	utils::{self, BoolExt, hash::verify_password, json::serialized_len, string::EMPTY},
22};
23use tuwunel_database::{Deserialized, Json, Map};
24
25use crate::users::is_password_hash;
26
27pub struct Service {
28	userdevicesessionid_uiaarequest: Mutex<Requests>,
29	db: Data,
30	services: Arc<crate::services::OnceServices>,
31}
32
33struct Data {
34	userdevicesessionid_uiaainfo: Arc<Map>,
35}
36
37type Requests = LruCache<RequestKey, CanonicalJsonValue>;
38type RequestKey = (OwnedUserId, OwnedDeviceId, String);
39
40pub const SESSION_ID_LENGTH: usize = 32;
41
42/// Maximum number of retained UIAA request bodies.
43///
44/// Inserting another session evicts the least recently used entry.
45const MAX_REQUESTS: usize = 1024;
46
47/// Maximum serialized body and owned key bytes per retained request.
48///
49/// Parsed JSON adds container overhead to this payload budget. Larger entries
50/// are not retained, so the client must resend the request fields.
51const MAX_REQUEST_BYTES: usize = 4_096;
52
53#[cfg(test)]
54mod tests;
55
56#[derive(Clone, Copy)]
57enum EmailIdentityMode {
58	Validate,
59	Claim,
60}
61
62struct Request<'a> {
63	user_id: &'a UserId,
64	device_id: &'a DeviceId,
65	auth: &'a AuthData,
66	uiaainfo: &'a UiaaInfo,
67	email_identity_mode: EmailIdentityMode,
68	client_ip: Option<IpAddr>,
69}
70
71impl crate::Service for Service {
72	fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
73		Ok(Arc::new(Self {
74			userdevicesessionid_uiaarequest: Requests::new(MAX_REQUESTS).into(),
75			db: Data {
76				userdevicesessionid_uiaainfo: args.db["userdevicesessionid_uiaainfo"].clone(),
77			},
78			services: args.services.clone(),
79		}))
80	}
81
82	fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
83}
84
85/// Creates a new Uiaa session. Make sure the session token is unique.
86#[implement(Service)]
87pub fn create(
88	&self,
89	user_id: &UserId,
90	device_id: &DeviceId,
91	uiaainfo: &UiaaInfo,
92	json_body: &CanonicalJsonValue,
93) {
94	// TODO: better session error handling (why is uiaainfo.session optional in
95	// ruma?)
96	let session = uiaainfo
97		.session
98		.as_ref()
99		.expect("session should be set");
100
101	self.set_uiaa_request(user_id, device_id, session, json_body);
102
103	self.update_uiaa_session(user_id, device_id, session, Some(uiaainfo));
104}
105
106/// Authenticate one stage without taking ownership of an email proof.
107///
108/// Generic UIAA consumers may validate email identity, but only registration
109/// assigns a durable owner to that proof.
110#[implement(Service)]
111pub async fn try_auth(
112	&self,
113	user_id: &UserId,
114	device_id: &DeviceId,
115	auth: &AuthData,
116	uiaainfo: &UiaaInfo,
117	client_ip: Option<IpAddr>,
118) -> Result<(bool, UiaaInfo)> {
119	self.try_auth_inner(Request {
120		user_id,
121		device_id,
122		auth,
123		uiaainfo,
124		email_identity_mode: EmailIdentityMode::Validate,
125		client_ip,
126	})
127	.await
128}
129
130/// Authenticate one registration stage and claim an email proof when present.
131///
132/// The claim is tied to the exact user, device, and UIAA session tuple before
133/// the email stage is recorded as complete.
134#[implement(Service)]
135pub async fn try_auth_registration(
136	&self,
137	user_id: &UserId,
138	device_id: &DeviceId,
139	auth: &AuthData,
140	uiaainfo: &UiaaInfo,
141	client_ip: Option<IpAddr>,
142) -> Result<(bool, UiaaInfo)> {
143	self.try_auth_inner(Request {
144		user_id,
145		device_id,
146		auth,
147		uiaainfo,
148		email_identity_mode: EmailIdentityMode::Claim,
149		client_ip,
150	})
151	.await
152}
153
154#[implement(Service)]
155async fn try_auth_inner(&self, request: Request<'_>) -> Result<(bool, UiaaInfo)> {
156	let Request {
157		user_id,
158		device_id,
159		auth,
160		uiaainfo,
161		email_identity_mode,
162		client_ip,
163	} = request;
164
165	let mut uiaainfo = if let Some(session) = auth.session() {
166		self.get_uiaa_session(user_id, device_id, session)
167			.await?
168	} else {
169		uiaainfo.clone()
170	};
171
172	if uiaainfo.session.is_none() {
173		uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
174	}
175
176	match auth {
177		// Find out what the user completed
178		| AuthData::Password(password) => {
179			let client_ip = client_ip
180				.ok_or_else(|| err!("Missing client address for password authentication."))?;
181
182			if let ControlFlow::Break(authed) = self
183				.verify_password(user_id, &mut uiaainfo, password, client_ip)
184				.await?
185			{
186				return Ok((authed, uiaainfo));
187			}
188		},
189		| AuthData::RegistrationToken(t) => {
190			let token = t.token.trim();
191			if self
192				.services
193				.registration_tokens
194				.try_consume(token)
195				.await
196				.is_ok()
197			{
198				uiaainfo
199					.completed
200					.push(AuthType::RegistrationToken);
201			} else {
202				uiaainfo.auth_error = Some(Box::new(StandardErrorBody {
203					kind: ErrorKind::forbidden(),
204					message: "Invalid registration token.".to_owned(),
205				}));
206
207				return Ok((false, uiaainfo));
208			}
209		},
210		| AuthData::FallbackAcknowledgement(_session) => {
211			// A fallback acknowledgement is a session re-poll. The fallback
212			// web handler (e.g. the SSO callback) is what records completion.
213		},
214		| AuthData::OAuth(_) => {
215			// MSC4312: OAuth cross-signing reset uses SSO re-authentication.
216			// If a bypass was granted via SSO re-auth, mark OAuth as completed.
217			if !uiaainfo.completed.contains(&AuthType::OAuth) {
218				if self
219					.services
220					.users
221					.can_replace_cross_signing_keys(user_id)
222					.await
223				{
224					uiaainfo.completed.push(AuthType::OAuth);
225				} else {
226					uiaainfo.auth_error = Some(Box::new(StandardErrorBody {
227						kind: ErrorKind::forbidden(),
228						message: "OAuth cross-signing reset not approved for this session."
229							.to_owned(),
230					}));
231
232					return Ok((false, uiaainfo));
233				}
234			}
235		},
236		| AuthData::Dummy(_) => {
237			uiaainfo.completed.push(AuthType::Dummy);
238		},
239		| AuthData::Terms(_) => {
240			// MSC1692: an empty auth dict accepts every presented policy.
241			uiaainfo.completed.push(AuthType::Terms);
242		},
243		| AuthData::EmailIdentity(EmailIdentity { thirdparty_id_creds, .. }) => {
244			// A stray id_server is tolerated and id_access_token is never required.
245			let validated = self
246				.authenticate_email_identity(
247					user_id,
248					device_id,
249					&uiaainfo,
250					thirdparty_id_creds,
251					email_identity_mode,
252				)
253				.await?;
254
255			if !validated {
256				uiaainfo.auth_error = Some(Box::new(StandardErrorBody {
257					kind: ErrorKind::forbidden(),
258					message: "Email address has not been validated.".to_owned(),
259				}));
260
261				return Ok((false, uiaainfo));
262			}
263
264			uiaainfo.completed.push(AuthType::EmailIdentity);
265		},
266		| auth => error!("AuthData type not supported: {auth:?}"),
267	}
268
269	// Check if a flow now succeeds
270	let mut completed = false;
271	'flows: for flow in &mut uiaainfo.flows {
272		for stage in &flow.stages {
273			if !uiaainfo.completed.contains(stage) {
274				continue 'flows;
275			}
276		}
277		// We didn't break, so this flow succeeded!
278		completed = true;
279	}
280
281	let session = uiaainfo
282		.session
283		.as_ref()
284		.expect("session is always set");
285
286	if matches!(email_identity_mode, EmailIdentityMode::Claim)
287		&& !matches!(auth, AuthData::EmailIdentity(_))
288		&& uiaainfo
289			.completed
290			.contains(&AuthType::EmailIdentity)
291	{
292		let claim = (user_id.to_owned(), device_id.to_owned(), session.as_str().into());
293
294		if !self
295			.services
296			.threepid
297			.refresh_claim(&claim)
298			.await?
299		{
300			uiaainfo
301				.completed
302				.retain(|stage| stage != &AuthType::EmailIdentity);
303
304			uiaainfo.auth_error = Some(Box::new(StandardErrorBody {
305				kind: ErrorKind::forbidden(),
306				message: "Email address has not been validated.".to_owned(),
307			}));
308
309			self.update_uiaa_session(user_id, device_id, session, Some(&uiaainfo));
310
311			return Ok((false, uiaainfo));
312		}
313	}
314
315	if !completed {
316		self.update_uiaa_session(user_id, device_id, session, Some(&uiaainfo));
317
318		return Ok((false, uiaainfo));
319	}
320
321	// Retain the session until registration spends its email claim.
322	let retain_session = matches!(email_identity_mode, EmailIdentityMode::Claim)
323		&& uiaainfo
324			.completed
325			.contains(&AuthType::EmailIdentity);
326
327	self.update_uiaa_session(user_id, device_id, session, retain_session.then_some(&uiaainfo));
328
329	Ok((true, uiaainfo))
330}
331
332#[implement(Service)]
333async fn authenticate_email_identity(
334	&self,
335	user_id: &UserId,
336	device_id: &DeviceId,
337	uiaainfo: &UiaaInfo,
338	creds: &ThirdpartyIdCredentials,
339	mode: EmailIdentityMode,
340) -> Result<bool> {
341	match mode {
342		| EmailIdentityMode::Validate => Ok(self
343			.services
344			.threepid
345			.session_validated(creds.sid.as_str(), creds.client_secret.as_str())
346			.await),
347		| EmailIdentityMode::Claim => {
348			let session = uiaainfo
349				.session
350				.as_ref()
351				.expect("session is always set");
352
353			let claim = (user_id.to_owned(), device_id.to_owned(), session.as_str().into());
354
355			self.services
356				.threepid
357				.claim_validated(creds.sid.as_str(), creds.client_secret.as_str(), claim)
358				.await
359		},
360	}
361}
362
363#[implement(Service)]
364async fn verify_password(
365	&self,
366	user_id: &UserId,
367	uiaainfo: &mut UiaaInfo,
368	password: &Password,
369	client_ip: IpAddr,
370) -> Result<ControlFlow<bool>> {
371	let Password { identifier, password, user, .. } = password;
372
373	let username = extract!(identifier, x in Some(UserIdentifier::Matrix(ruma::api::client::uiaa::MatrixUserIdentifier { user: x, .. })))
374		.or_else(|| cfg!(feature = "element_hacks").and(user.as_ref()))
375		.ok_or(err!(Request(Unrecognized("Identifier type not recognized."))))?;
376
377	let user_id_from_username =
378		UserId::parse_with_server_name(username.clone(), self.services.globals.server_name())
379			.map_err(|_| err!(Request(InvalidParam("User ID is invalid."))))?;
380
381	// Check if the access token being used matches the credentials used for UIAA
382	if user_id.localpart() != user_id_from_username.localpart() {
383		return Err!(Request(Forbidden("User ID and access token mismatch.")));
384	}
385
386	// A stolen access token must not become an unlimited password oracle.
387	let reservation = self
388		.services
389		.login_ratelimit
390		.reserve_uiaa_attempt(user_id, client_ip)?;
391
392	// First try local password hash verification; `None` when the account has
393	// no local password to check.
394	let verified = self
395		.services
396		.users
397		.password_hash(user_id)
398		.await
399		.ok()
400		.filter(|hash| is_password_hash(hash))
401		.map(|hash| verify_password(password, &hash).is_ok());
402
403	// Only LDAP-origin accounts fall back to LDAP; others would trigger a
404	// directory-wide search.
405	#[cfg(feature = "ldap")]
406	let verified = if verified != Some(true)
407		&& self.services.server.config.ldap.enable
408		&& self
409			.services
410			.users
411			.origin(user_id)
412			.await
413			.is_ok_and(|origin| origin == "ldap")
414		&& let Ok(dns) = self.services.users.search_ldap(user_id).await
415		&& let Some((user_dn, _is_admin)) = dns.first()
416	{
417		let bound = self
418			.services
419			.users
420			.auth_ldap(user_dn, password)
421			.await
422			.is_ok();
423
424		Some(bound)
425	} else {
426		verified
427	};
428
429	// Only the failed-attempt axis, since re-entering a password opens no
430	// session; a password checked and refused keeps the reservation.
431	if verified != Some(false) {
432		self.services
433			.login_ratelimit
434			.refund_login_attempt(reservation)?;
435	}
436
437	if verified != Some(true) {
438		uiaainfo.auth_error = Some(Box::new(StandardErrorBody {
439			kind: ErrorKind::forbidden(),
440			message: "Invalid username or password.".to_owned(),
441		}));
442
443		return Ok(ControlFlow::Break(false));
444	}
445
446	uiaainfo.completed.push(AuthType::Password);
447
448	Ok(ControlFlow::Continue(()))
449}
450
451#[implement(Service)]
452fn set_uiaa_request(
453	&self,
454	user_id: &UserId,
455	device_id: &DeviceId,
456	session: &str,
457	request: &CanonicalJsonValue,
458) {
459	let available = MAX_REQUEST_BYTES
460		.saturating_sub(user_id.as_str().len())
461		.saturating_sub(device_id.as_str().len())
462		.saturating_sub(session.len());
463
464	if !serialized_len(request).is_ok_and(|len| len <= available) {
465		return;
466	}
467
468	let key = (user_id.to_owned(), device_id.to_owned(), session.to_owned());
469
470	self.userdevicesessionid_uiaarequest
471		.lock()
472		.expect("locked")
473		.insert(key, request.to_owned());
474}
475
476#[implement(Service)]
477pub fn get_uiaa_request(
478	&self,
479	user_id: &UserId,
480	device_id: Option<&DeviceId>,
481	session: &str,
482) -> Option<CanonicalJsonValue> {
483	let device_id = device_id.unwrap_or_else(|| EMPTY.into());
484	let key = (user_id.to_owned(), device_id.to_owned(), session.to_owned());
485
486	self.userdevicesessionid_uiaarequest
487		.lock()
488		.expect("locked")
489		.get_mut(&key)
490		.cloned()
491}
492
493#[implement(Service)]
494pub fn update_uiaa_session(
495	&self,
496	user_id: &UserId,
497	device_id: &DeviceId,
498	session: &str,
499	uiaainfo: Option<&UiaaInfo>,
500) {
501	let key = (user_id, device_id, session);
502
503	if let Some(uiaainfo) = uiaainfo {
504		self.db
505			.userdevicesessionid_uiaainfo
506			.put(key, Json(uiaainfo));
507	} else {
508		self.db.userdevicesessionid_uiaainfo.del(key);
509
510		let key = (user_id.to_owned(), device_id.to_owned(), session.to_owned());
511
512		self.userdevicesessionid_uiaarequest
513			.lock()
514			.expect("locked")
515			.remove(&key);
516	}
517}
518
519#[implement(Service)]
520async fn get_uiaa_session(
521	&self,
522	user_id: &UserId,
523	device_id: &DeviceId,
524	session: &str,
525) -> Result<UiaaInfo> {
526	let key = (user_id, device_id, session);
527
528	self.db
529		.userdevicesessionid_uiaainfo
530		.qry(&key)
531		.await
532		.deserialized()
533		.map_err(|_| err!(Request(Forbidden("UIAA session does not exist."))))
534}
535
536#[implement(Service)]
537pub async fn get_uiaa_session_by_session_id(
538	&self,
539	session_id: &str,
540) -> Option<(OwnedUserId, OwnedDeviceId, UiaaInfo)> {
541	// Iterate over keys only (fastest way without a secondary index)
542	let stream = self
543		.db
544		.userdevicesessionid_uiaainfo
545		.keys::<(OwnedUserId, OwnedDeviceId, String)>();
546
547	pin_mut!(stream);
548	while let Ok(Some((user_id, device_id, session))) = stream.try_next().await {
549		if session == session_id {
550			// Found the key, now fetch the actual UiaaInfo
551			if let Ok(uiaainfo) = self
552				.get_uiaa_session(&user_id, &device_id, session_id)
553				.await
554			{
555				return Some((user_id, device_id, uiaainfo));
556			}
557		}
558	}
559
560	None
561}