Skip to main content

tuwunel_api/router/auth/
uiaa.rs

1use std::borrow::Cow;
2
3use ruma::{
4	CanonicalJsonValue, DeviceId, OwnedUserId, UserId,
5	api::{
6		IncomingRequest,
7		client::uiaa::{AuthData, AuthFlow, AuthType, UiaaInfo},
8	},
9};
10use serde_json::{json, value::to_raw_value};
11use tuwunel_core::{
12	Err, Error, Result, err, is_equal_to, utils,
13	utils::{
14		BoolExt, OptionExt,
15		future::{OptionFutureExt, TryExtExt},
16	},
17};
18use tuwunel_service::{Services, uiaa::SESSION_ID_LENGTH};
19
20#[cfg(feature = "jwt_login")]
21use super::jwt::validate_user;
22use crate::Ruma;
23
24/// Authenticates a user through the request's UIAA flow.
25///
26/// The configured authentication stages determine whether the flow is complete.
27pub async fn auth_uiaa<T>(services: &Services, body: &Ruma<T>) -> Result<OwnedUserId>
28where
29	T: IncomingRequest + Send + Sync,
30{
31	let sender_user = body.sender_user.as_deref();
32
33	let password_flow = [AuthType::Password];
34	let user_origin = sender_user
35		.map_async(|sender_user| services.users.origin(sender_user).ok())
36		.unwrap_or(None)
37		.await;
38
39	let ldap_origin = cfg!(feature = "ldap")
40		&& services.config.ldap.enable
41		&& user_origin.as_deref() == Some("ldap");
42
43	let has_password = ldap_origin
44		|| sender_user
45			.map_async(|sender_user| {
46				services
47					.users
48					.has_password(sender_user)
49					.unwrap_or(false)
50			})
51			.unwrap_or(false)
52			.await;
53
54	let sso_flow = [AuthType::Sso];
55	let bound_idp = sender_user
56		.map_async(|sender_user| {
57			select_idp(
58				services,
59				sender_user,
60				body.sender_device.as_deref(),
61				user_origin.as_deref(),
62			)
63		})
64		.await
65		.flatten();
66
67	let has_sso = bound_idp.is_some();
68
69	let jwt_flow = [AuthType::Jwt];
70	let has_jwt = cfg!(feature = "jwt_login") && services.config.jwt.enable;
71
72	let mut uiaainfo = UiaaInfo {
73		flows: has_password
74			.then_some(password_flow)
75			.into_iter()
76			.chain(has_sso.then_some(sso_flow))
77			.chain(has_jwt.then_some(jwt_flow))
78			.map(Vec::from)
79			.map(AuthFlow::new)
80			.collect(),
81
82		params: to_raw_value(&json!({})).ok(),
83		..Default::default()
84	};
85
86	match body
87		.json_body
88		.as_ref()
89		.and_then(CanonicalJsonValue::as_object)
90		.and_then(|body| body.get("auth"))
91		.cloned()
92		.map(CanonicalJsonValue::into)
93		.map(serde_json::from_value)
94		.transpose()?
95	{
96		#[cfg(feature = "jwt_login")]
97		| Some(AuthData::Jwt(ref jwt)) => {
98			let sender_user = validate_user(services, &jwt.token)?;
99
100			if !services.users.exists(&sender_user).await {
101				return Err!(Request(NotFound("User {sender_user} is not registered.")));
102			}
103
104			services
105				.users
106				.deactivated_check(&sender_user)
107				.await?;
108
109			// Success!
110			Ok(sender_user)
111		},
112		#[cfg(not(feature = "jwt_login"))]
113		| Some(AuthData::Jwt(_)) => Err!(Request(Unauthorized("JWT login is not enabled."))),
114		| Some(ref auth) => {
115			let sender_user = body
116				.sender_user
117				.as_deref()
118				.ok_or_else(|| err!(Request(MissingToken("Missing access token."))))?;
119
120			let sender_device = body.sender_device()?;
121			let (worked, uiaainfo) = services
122				.uiaa
123				.try_auth(sender_user, sender_device, auth, &uiaainfo, body.rate_limit_ip.ok())
124				.await?;
125
126			if !worked {
127				return Err(Error::Uiaa(uiaainfo));
128			}
129
130			// Success!
131			Ok(sender_user.to_owned())
132		},
133		| _ => match body.json_body {
134			| Some(ref json) => {
135				let sender_user = body
136					.sender_user
137					.as_deref()
138					.ok_or_else(|| err!(Request(MissingToken("Missing access token."))))?;
139
140				let sender_device = body.sender_device()?;
141				uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
142
143				// The SSO fallback page routes re-authentication to the provider bound here.
144				if let Some(ref idp) = bound_idp {
145					uiaainfo.params = to_raw_value(&json!({
146						"m.login.sso": {
147							"identity_providers": [{"id": idp}]
148						}
149					}))
150					.ok();
151				}
152
153				services
154					.uiaa
155					.create(sender_user, sender_device, &uiaainfo, json);
156
157				Err(Error::Uiaa(uiaainfo))
158			},
159			| _ => Err!(Request(NotJson("JSON body is not valid"))),
160		},
161	}
162}
163
164/// Choose the identity provider to bind to the UIAA session's SSO stage.
165///
166/// A device the OIDC token endpoint tagged binds its own provider. Otherwise an
167/// `sso` account on a single-provider server binds that provider. Failing both,
168/// it binds a configured provider that one of the account's sessions links,
169/// preferring the default. The SSO callback completes the stage only for an
170/// identity that resolves to the UIAA session's owner.
171async fn select_idp<'a>(
172	services: &'a Services,
173	sender_user: &UserId,
174	sender_device: Option<&DeviceId>,
175	user_origin: Option<&str>,
176) -> Option<Cow<'a, str>> {
177	let tagged = sender_device
178		.map_async(|device_id| {
179			services
180				.users
181				.get_oidc_device_idp(sender_user, device_id)
182		})
183		.await
184		.flatten()
185		.map(Cow::Owned)
186		.or_else(|| {
187			let single = user_origin.is_some_and(is_equal_to!("sso"))
188				&& services.config.identity_provider.len() == 1;
189
190			single
191				.and_then(|| services.oauth.providers.find_default_config())
192				.map(|provider| Cow::Borrowed(provider.id()))
193		});
194
195	tagged
196		.is_none()
197		.then_async(|| {
198			services
199				.oauth
200				.sessions
201				.linked_provider(sender_user)
202		})
203		.await
204		.flatten()
205		.map(Cow::Borrowed)
206		.or(tagged)
207}