Skip to main content

tuwunel_api/router/auth/
dispatch.rs

1use std::any::TypeId;
2
3use ruma::{
4	CanonicalJsonValue,
5	api::{
6		auth_scheme::{
7			AccessToken, AccessTokenOptional, AppserviceToken, AppserviceTokenOptional,
8			AuthScheme, NoAccessToken, NoAuthentication,
9		},
10		client::{
11			account::change_password, delayed_events::update_delayed_event, rtc::transports,
12		},
13		federation::authentication::ServerSignatures,
14	},
15};
16use tuwunel_core::{Err, Error, Result};
17use tuwunel_service::Services;
18
19use super::{Auth, Request, Token, appservice::auth_appservice, server::auth_server};
20
21/// Tag identifying an [`AuthScheme`] for tuwunel's purposes.
22///
23/// Ruma's `AuthScheme` is a trait, so endpoint-specific bypasses cannot be
24/// expressed as enum match arms anymore. This tag is the value-side handle
25/// used to route through `auth()` and to identify the unauthenticated case
26/// inside `check_auth_still_required`.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub(in crate::router) enum Scheme {
29	None,
30	AccessToken,
31	AccessTokenOptional,
32	AppserviceToken,
33	AppserviceTokenOptional,
34	ServerSignatures,
35}
36
37/// Trait routing a concrete [`AuthScheme`] through the per-scheme dispatch.
38///
39/// `dispatch` is intentionally non-generic over the request type; the
40/// caller passes `TypeId::of::<T>()` so each impl emits a single body
41/// rather than monomorphizing per request.
42pub(in crate::router) trait AuthDispatch: AuthScheme {
43	const SCHEME: Scheme;
44
45	fn dispatch(
46		services: &Services,
47		request: &mut Request,
48		json_body: Option<&CanonicalJsonValue>,
49		token: Token,
50		route: TypeId,
51	) -> impl Future<Output = Result<Auth>> + Send;
52}
53
54impl AuthDispatch for NoAccessToken {
55	const SCHEME: Scheme = Scheme::None;
56
57	async fn dispatch(
58		services: &Services,
59		request: &mut Request,
60		json_body: Option<&CanonicalJsonValue>,
61		token: Token,
62		route: TypeId,
63	) -> Result<Auth> {
64		<NoAuthentication as AuthDispatch>::dispatch(services, request, json_body, token, route)
65			.await
66	}
67}
68
69impl AuthDispatch for NoAuthentication {
70	const SCHEME: Scheme = Scheme::None;
71
72	async fn dispatch(
73		_services: &Services,
74		_request: &mut Request,
75		_json_body: Option<&CanonicalJsonValue>,
76		token: Token,
77		_route: TypeId,
78	) -> Result<Auth> {
79		match token {
80			// check_auth_still_required already enforced any auth-required config for
81			// these no-auth routes, so a stale or unknown token serves anonymously.
82			| Token::Invalid | Token::Expired | Token::None => Ok(Auth::default()),
83
84			| Token::User(user) => Ok(Auth {
85				sender_user: Some(user.0),
86				sender_device: Some(user.1),
87				_expires_at: user.2,
88				..Auth::default()
89			}),
90
91			| Token::Appservice(info) => Ok(Auth {
92				appservice_info: Some(*info),
93				..Auth::default()
94			}),
95		}
96	}
97}
98
99impl AuthDispatch for AccessToken {
100	const SCHEME: Scheme = Scheme::AccessToken;
101
102	async fn dispatch(
103		services: &Services,
104		request: &mut Request,
105		_json_body: Option<&CanonicalJsonValue>,
106		token: Token,
107		route: TypeId,
108	) -> Result<Auth> {
109		match token {
110			| Token::Invalid => unknown_token(),
111			| Token::Expired => expired_token(),
112			| Token::Appservice(info) => Ok(auth_appservice(services, request, info).await?),
113			| Token::User(user) => Ok(Auth {
114				sender_user: Some(user.0),
115				sender_device: Some(user.1),
116				_expires_at: user.2,
117				..Auth::default()
118			}),
119			| Token::None if allows_missing_access_token(route) => Ok(Auth::default()),
120
121			| Token::None => Err!(Request(MissingToken("Missing access token."))),
122		}
123	}
124}
125
126/// Allow endpoints with a dedicated unauthenticated authorization path through
127/// the request authentication gate.
128///
129/// Transport discovery exposes only configured public metadata. Password reset
130/// derives its target from a validated and bound email proof in the route. A
131/// delayed event action names its event by an unguessable `delay_id`, and the
132/// route refuses a missing token on its stable path.
133fn allows_missing_access_token(route: TypeId) -> bool {
134	route == TypeId::of::<transports::v1::Request>()
135		|| route == TypeId::of::<change_password::v3::Request>()
136		|| route == TypeId::of::<update_delayed_event::v1::Request>()
137}
138
139impl AuthDispatch for AccessTokenOptional {
140	const SCHEME: Scheme = Scheme::AccessTokenOptional;
141
142	async fn dispatch(
143		_services: &Services,
144		_request: &mut Request,
145		_json_body: Option<&CanonicalJsonValue>,
146		token: Token,
147		_route: TypeId,
148	) -> Result<Auth> {
149		match token {
150			| Token::Invalid => unknown_token(),
151			| Token::Expired => expired_token(),
152			| Token::User(user) => Ok(Auth {
153				sender_user: Some(user.0),
154				sender_device: Some(user.1),
155				_expires_at: user.2,
156				..Auth::default()
157			}),
158			| Token::Appservice(info) => Ok(Auth {
159				appservice_info: Some(*info),
160				..Auth::default()
161			}),
162			| Token::None => Ok(Auth::default()),
163		}
164	}
165}
166
167impl AuthDispatch for AppserviceToken {
168	const SCHEME: Scheme = Scheme::AppserviceToken;
169
170	async fn dispatch(
171		_services: &Services,
172		_request: &mut Request,
173		_json_body: Option<&CanonicalJsonValue>,
174		token: Token,
175		_route: TypeId,
176	) -> Result<Auth> {
177		match token {
178			| Token::Invalid => unknown_token(),
179			| Token::Expired => expired_token(),
180			| Token::User(_) =>
181				Err!(Request(Forbidden("Appservice tokens must be used on this endpoint."))),
182			| Token::Appservice(info) => Ok(Auth {
183				appservice_info: Some(*info),
184				..Auth::default()
185			}),
186			| Token::None => Err!(Request(MissingToken("Missing access token."))),
187		}
188	}
189}
190
191impl AuthDispatch for AppserviceTokenOptional {
192	const SCHEME: Scheme = Scheme::AppserviceTokenOptional;
193
194	async fn dispatch(
195		_services: &Services,
196		_request: &mut Request,
197		_json_body: Option<&CanonicalJsonValue>,
198		token: Token,
199		_route: TypeId,
200	) -> Result<Auth> {
201		match token {
202			| Token::Invalid => unknown_token(),
203			| Token::Expired => expired_token(),
204			| Token::User(user) => Ok(Auth {
205				sender_user: Some(user.0),
206				sender_device: Some(user.1),
207				_expires_at: user.2,
208				..Auth::default()
209			}),
210			| Token::Appservice(info) => Ok(Auth {
211				appservice_info: Some(*info),
212				..Auth::default()
213			}),
214			| Token::None => Ok(Auth::default()),
215		}
216	}
217}
218
219impl AuthDispatch for ServerSignatures {
220	const SCHEME: Scheme = Scheme::ServerSignatures;
221
222	async fn dispatch(
223		services: &Services,
224		request: &mut Request,
225		json_body: Option<&CanonicalJsonValue>,
226		token: Token,
227		_route: TypeId,
228	) -> Result<Auth> {
229		match token {
230			| Token::Invalid => unknown_token(),
231			| Token::Expired => expired_token(),
232			| Token::Appservice(_) | Token::User(_) =>
233				Err!(Request(Unauthorized("Server signatures must be used on this endpoint."))),
234			| Token::None => Ok(auth_server(services, request, json_body).await?),
235		}
236	}
237}
238
239fn unknown_token() -> Result<Auth> {
240	let soft_logout = false;
241
242	Err(Error::unknown_token(soft_logout, "Unknown access token."))
243}
244
245// Kept until a later device token expires, so a retry or concurrent request reads as expired.
246fn expired_token() -> Result<Auth> {
247	let soft_logout = true;
248
249	Err(Error::unknown_token(soft_logout, "Expired access token."))
250}
251
252#[cfg(test)]
253mod tests {
254	use ruma::api::client::{
255		delayed_events::update_delayed_event::unstable_v1::Request as UpdateByBodyRequest,
256		discovery::get_supported_versions,
257	};
258
259	use super::*;
260
261	#[test]
262	fn dedicated_routes_bypass_access_token_auth() {
263		assert!(allows_missing_access_token(TypeId::of::<transports::v1::Request>()));
264		assert!(allows_missing_access_token(TypeId::of::<change_password::v3::Request>()));
265		assert!(allows_missing_access_token(TypeId::of::<update_delayed_event::v1::Request>()));
266		assert!(!allows_missing_access_token(TypeId::of::<get_supported_versions::Request>()));
267		assert!(!allows_missing_access_token(TypeId::of::<UpdateByBodyRequest>()));
268	}
269}