Skip to main content

tuwunel_api/router/
args.rs

1use std::{any::TypeId, fmt::Debug, net::IpAddr, ops::Deref};
2
3use axum::{body::Body, extract::FromRequest};
4use axum_extra::extract::cookie::CookieJar;
5use bytes::{BufMut, Bytes, BytesMut};
6use http::{Method, Request as HttpRequest};
7use ruma::{
8	CanonicalJsonObject, CanonicalJsonValue, DeviceId, OwnedDeviceId, OwnedServerName,
9	OwnedUserId, ServerName, UserId,
10	api::{
11		IncomingRequest,
12		client::{
13			appservice::fed_proxy::unstable::Request as FedProxyRequest,
14			media::{
15				create_content::v3::Request as UploadRequest,
16				create_content_async::v3::Request as AsyncUploadRequest,
17			},
18			membership::is_joined::unstable::Request as IsJoinedRequest,
19		},
20		error::{DeserializationError, FromHttpRequestError},
21	},
22};
23use serde_json::{Value as JsonValue, from_slice};
24use tuwunel_core::{Err, Error, Result, err, implement, utils::string::EMPTY};
25use tuwunel_service::{Services, appservice::RegistrationInfo};
26
27use super::{
28	auth::{Auth, AuthDispatch, Scheme, admin::require_admin, auth},
29	client_ip::rate_limit_ip,
30	request::{Request, from as request_from},
31};
32use crate::State;
33
34/// Extracts a typed Ruma request and its authentication context.
35///
36/// Administrator-only routes defer JSON errors until authorization succeeds.
37/// Ordinary routes reject malformed JSON before authentication.
38#[derive(Debug)]
39pub struct Args<T, const ADMIN: bool = false> {
40	/// Request struct body
41	pub body: T,
42
43	/// Cookies received from the useragent.
44	pub cookie: CookieJar,
45
46	/// Authenticated X-Matrix origin, absent for non-federation requests.
47	pub origin: Option<OwnedServerName>,
48
49	/// Authenticated local user, absent when no local user is identified.
50	pub sender_user: Option<OwnedUserId>,
51
52	/// Authenticated local device, absent for device-less authentication.
53	pub sender_device: Option<OwnedDeviceId>,
54
55	/// Authenticated appservice registration, absent for other callers.
56	pub appservice_info: Option<RegistrationInfo>,
57
58	/// Parsed canonical JSON, absent for raw or noncanonical request bodies.
59	pub json_body: Option<CanonicalJsonValue>,
60
61	/// Client address for password throttling, resolved independently of legacy IP hints.
62	pub rate_limit_ip: Result<IpAddr, &'static str>,
63}
64
65/// Requires administrator authorization before returning request body errors.
66///
67/// Routes opt in through this alias; the default extractor retains its ordering.
68pub type ArgsAdmin<T> = Args<T, true>;
69
70/// Returns the user authenticated for a route requiring a user identity.
71///
72/// Panics if the endpoint's authentication scheme did not identify a user.
73#[implement(
74	Args,
75	generics = "<T, const ADMIN: bool>",
76	params = "<T, ADMIN>"
77)]
78#[inline]
79pub fn sender_user(&self) -> &UserId {
80	self.sender_user
81		.as_deref()
82		.expect("user must be authenticated for this handler")
83}
84
85/// Returns the server authenticated for a federation route.
86///
87/// Panics if the endpoint's authentication scheme did not identify a server.
88#[implement(
89	Args,
90	generics = "<T, const ADMIN: bool>",
91	params = "<T, ADMIN>"
92)]
93#[inline]
94pub fn origin(&self) -> &ServerName {
95	self.origin
96		.as_deref()
97		.expect("server must be authenticated for this handler")
98}
99
100/// Returns the authenticated device or rejects a device-less request.
101///
102/// User authentication alone does not guarantee a device identity.
103#[implement(
104	Args,
105	generics = "<T, const ADMIN: bool>",
106	params = "<T, ADMIN>"
107)]
108#[inline]
109pub fn sender_device(&self) -> Result<&DeviceId> {
110	self.sender_device
111		.as_deref()
112		.ok_or(err!(Request(Forbidden("user must be authenticated and device identified"))))
113}
114
115impl<T, const ADMIN: bool> Deref for Args<T, ADMIN>
116where
117	T: Sync,
118{
119	type Target = T;
120
121	fn deref(&self) -> &Self::Target { &self.body }
122}
123
124impl<T, const ADMIN: bool> FromRequest<State, Body> for Args<T, ADMIN>
125where
126	T: IncomingRequest + Debug + Send + Sync + 'static,
127	T::Authentication: AuthDispatch,
128{
129	type Rejection = Error;
130
131	#[tracing::instrument(name = "ar", level = "debug", skip_all, err(level = "debug"))]
132	async fn from_request(
133		request: HttpRequest<Body>,
134		services: &State,
135	) -> Result<Self, Self::Rejection> {
136		let route = TypeId::of::<T>();
137		let scheme = T::Authentication::SCHEME;
138		let request = request_from(services, request).await?;
139		let json_body = match ADMIN {
140			| true => parse_json(&request, route, scheme),
141			| false => Ok(parse_json(&request, route, scheme)?),
142		};
143
144		let json = json_body.as_ref().ok().and_then(Option::as_ref);
145		let (request, auth) = authenticate::<T>(request, services, json, route).await?;
146
147		_ = request
148			.parts
149			.extensions
150			.get::<tracing::Span>()
151			.inspect(|span| record_auth_context(span, &auth));
152
153		if ADMIN {
154			let sender = auth.sender_user.as_deref().ok_or_else(|| {
155				err!(Request(Forbidden("Only server administrators can use this endpoint")))
156			})?;
157
158			require_admin(services, sender).await?;
159		}
160
161		make_args(services, request, json_body?, auth, route)
162	}
163}
164
165pub(super) fn record_auth_context(span: &tracing::Span, auth: &Auth) {
166	_ = auth
167		.sender_user
168		.as_deref()
169		.inspect(|sender_user| {
170			span.record("user_id", sender_user.as_str());
171		});
172
173	_ = auth
174		.sender_device
175		.as_deref()
176		.inspect(|sender_device| {
177			span.record("device_id", sender_device.as_str());
178		});
179
180	_ = auth.origin.as_deref().inspect(|origin| {
181		span.record("origin", origin.as_str());
182	});
183}
184
185/// Parses canonical JSON while retaining ordinary JSON for typed deserialization.
186///
187/// A raw-body route's bytes are never parsed and pass through unchanged. Empty
188/// POST and DELETE bodies on other routes become objects for UIA.
189/// A server-signed body must be canonical JSON because its signature covers only
190/// the canonical form; only a zero-byte body is authenticated without content.
191pub(super) fn parse_json(
192	request: &Request,
193	route: TypeId,
194	scheme: Scheme,
195) -> Result<Option<CanonicalJsonValue>> {
196	if takes_raw_body(route) {
197		return Ok(None);
198	}
199
200	let json_body = from_slice(&request.body).ok();
201	let signed = scheme == Scheme::ServerSignatures;
202	let json_endpoint = signed
203		|| matches!(
204			request.parts.method,
205			Method::POST | Method::PUT | Method::DELETE | Method::PATCH
206		);
207
208	if json_body.is_some() || !json_endpoint {
209		return Ok(json_body);
210	}
211
212	let empty = match signed {
213		| true => request.body.is_empty(),
214		| false => request.body.iter().all(u8::is_ascii_whitespace),
215	};
216
217	if !empty {
218		from_slice::<JsonValue>(&request.body)
219			.map_err(|_| err!(Request(NotJson("Request body is not valid JSON."))))?;
220
221		if signed {
222			return Err!(Request(BadJson("Request body is not canonical JSON.")));
223		}
224	}
225
226	let empty_object = (empty && matches!(request.parts.method, Method::POST | Method::DELETE))
227		.then(|| CanonicalJsonValue::Object(CanonicalJsonObject::new()));
228
229	Ok(empty_object)
230}
231
232/// Identifies the routes whose request body is an uploaded file, not JSON.
233///
234/// These are the media uploads the specification exempts from JSON request
235/// bodies and the only ruma requests declaring a raw body; a new one belongs
236/// here too, so its bytes are stored and served exactly as sent.
237fn takes_raw_body(route: TypeId) -> bool {
238	route == TypeId::of::<UploadRequest>() || route == TypeId::of::<AsyncUploadRequest>()
239}
240
241/// Authenticates a request while retaining the headers consumed by extraction.
242///
243/// The parsed canonical body remains available to federation authentication.
244async fn authenticate<T>(
245	mut request: Request,
246	services: &State,
247	json_body: Option<&CanonicalJsonValue>,
248	route: TypeId,
249) -> Result<(Request, Auth)>
250where
251	T: IncomingRequest + Debug + Send + Sync + 'static,
252	T::Authentication: AuthDispatch,
253{
254	let auth = auth::<T::Authentication>(services, &mut request, json_body, route).await?;
255
256	Ok((request, auth))
257}
258
259/// Builds typed arguments after authentication and any UIA body merge.
260///
261/// Re-serializing an object body canonically, merged or not, is deliberate: a
262/// duplicate key keeps its last value, as in Synapse, and a federation request
263/// parses from the content its X-Matrix signature was checked against.
264///
265/// Transfers the original HTTP parts without cloning headers or the URI.
266fn make_args<T, const ADMIN: bool>(
267	services: &Services,
268	request: Request,
269	json_body: Option<CanonicalJsonValue>,
270	auth: Auth,
271	route: TypeId,
272) -> Result<Args<T, ADMIN>>
273where
274	T: IncomingRequest,
275{
276	let json_body = json_body.map(|json| match json {
277		| CanonicalJsonValue::Object(json) => restore_body(services, json, &auth).into(),
278		| json => json,
279	});
280
281	let body = json_body
282		.as_ref()
283		.filter(|json| json.is_object())
284		.map_or(request.body, serialize_body);
285
286	let rate_limit_ip = rate_limit_ip(&request.parts).map_err(|(_, message)| message);
287	let http_request = HttpRequest::from_parts(request.parts, body);
288	let body = T::try_from_http_request(http_request, &request.path)
289		.map_err(|e| parse_error(route, &e))?;
290
291	Ok(Args {
292		body,
293		cookie: request.cookie,
294		origin: auth.origin,
295		sender_user: auth.sender_user,
296		sender_device: auth.sender_device,
297		appservice_info: auth.appservice_info,
298		json_body,
299		rate_limit_ip,
300	})
301}
302
303/// Restores omitted fields from a UIA session before typed body parsing.
304///
305/// Current request fields take precedence over the saved initial request.
306fn restore_body(
307	services: &Services,
308	json_body: CanonicalJsonObject,
309	auth: &Auth,
310) -> CanonicalJsonObject {
311	let uiaa_request = json_body
312		.get("auth")
313		.and_then(CanonicalJsonValue::as_object)
314		.and_then(|auth| auth.get("session"))
315		.and_then(CanonicalJsonValue::as_str)
316		.and_then(|session| {
317			let user_id = auth.sender_user.clone().unwrap_or_else(|| {
318				UserId::parse_with_server_name(EMPTY, services.globals.server_name())
319					.expect("valid user_id")
320			});
321
322			services
323				.uiaa
324				.get_uiaa_request(&user_id, auth.sender_device.as_deref(), session)
325		});
326
327	uiaa_request
328		.and_then(|json| match json {
329			| CanonicalJsonValue::Object(json) => Some(json),
330			| _ => None,
331		})
332		.into_iter()
333		.flatten()
334		.fold(json_body, |mut json, (key, value)| {
335			json.entry(key).or_insert(value);
336
337			json
338		})
339}
340
341/// Serializes a canonical body directly into the HTTP byte buffer.
342///
343/// Canonical JSON values are always serializable, including restored UIA bodies.
344pub(super) fn serialize_body(json_body: &CanonicalJsonValue) -> Bytes {
345	let mut buf = BytesMut::new().writer();
346
347	serde_json::to_writer(&mut buf, json_body).expect("value serialization can't fail");
348
349	buf.into_inner().freeze()
350}
351
352/// Maps a request that failed to parse to its error.
353///
354/// Malformed input answers `M_BAD_JSON`. On the routes whose MSC names
355/// parameter errors, an absent required field answers `M_MISSING_PARAM`
356/// instead, and any other unparsable value, path and query parameters
357/// included, answers `M_INVALID_PARAM`.
358fn parse_error(route: TypeId, error: &FromHttpRequestError) -> Error {
359	match error {
360		| _ if !names_param_errors(route) => err!(Request(BadJson(debug_warn!("{error}")))),
361		| error if is_missing_field(error) => err!(Request(MissingParam(debug_warn!("{error}")))),
362		| _ => err!(Request(InvalidParam(debug_warn!("{error}")))),
363	}
364}
365
366/// Identifies the routes whose MSC names the errcodes for unparsable input.
367///
368/// These are MSC4502's `is_joined` and MSC4512's `fed_proxy`.
369fn names_param_errors(route: TypeId) -> bool {
370	route == TypeId::of::<IsJoinedRequest>() || route == TypeId::of::<FedProxyRequest>()
371}
372
373/// Reports whether a body failed to parse on an absent required field.
374///
375/// serde_json does not expose the case structurally, so this reads the message
376/// serde's `de::Error::missing_field` writes. Only bodies are checked: neither
377/// route has a required query parameter, and a matched route has its path.
378fn is_missing_field(error: &FromHttpRequestError) -> bool {
379	matches!(
380		error,
381		FromHttpRequestError::Deserialization(DeserializationError::Json(error))
382			if error.is_data() && error.to_string().starts_with("missing field")
383	)
384}
385
386#[cfg(test)]
387mod tests {
388	use std::any::TypeId;
389
390	use axum::extract::Path;
391	use axum_extra::extract::cookie::CookieJar;
392	use bytes::Bytes;
393	use http::{Method, Request as HttpRequest, StatusCode};
394	use ruma::{CanonicalJsonValue, api::error::ErrorKind};
395
396	use super::{Request, Scheme, parse_json};
397	use crate::router::request::{PathParams, QueryParams};
398
399	#[test]
400	fn signed_body_must_be_canonical() {
401		for method in [Method::GET, Method::PUT, Method::POST] {
402			for body in [r#"{"x":0.5}"#, r#"{"x":9007199254740992}"#] {
403				let request = request(method.clone(), body);
404				let error = parse_json(&request, TypeId::of::<()>(), Scheme::ServerSignatures)
405					.unwrap_err();
406
407				assert_eq!(error.status_code(), StatusCode::BAD_REQUEST);
408				assert_eq!(error.kind(), ErrorKind::BadJson);
409			}
410		}
411	}
412
413	#[test]
414	fn client_body_stays_lenient() {
415		for method in [Method::PUT, Method::POST] {
416			for scheme in [Scheme::AccessToken, Scheme::None] {
417				let request = request(method.clone(), r#"{"x":0.5}"#);
418
419				assert_eq!(parse_json(&request, TypeId::of::<()>(), scheme).unwrap(), None);
420			}
421		}
422
423		for scheme in [Scheme::AccessToken, Scheme::None] {
424			let request = request(Method::POST, " \t\r\n");
425
426			assert_eq!(
427				parse_json(&request, TypeId::of::<()>(), scheme).unwrap(),
428				Some(CanonicalJsonValue::Object(Default::default()))
429			);
430		}
431	}
432
433	#[test]
434	fn signed_empty_body_unchanged() {
435		let put = request(Method::PUT, "");
436		let post = request(Method::POST, "");
437		let scheme = Scheme::ServerSignatures;
438
439		assert_eq!(parse_json(&put, TypeId::of::<()>(), scheme).unwrap(), None);
440		assert_eq!(
441			parse_json(&post, TypeId::of::<()>(), scheme).unwrap(),
442			Some(CanonicalJsonValue::Object(Default::default()))
443		);
444	}
445
446	#[test]
447	fn signed_garbage_body_is_not_json() {
448		for method in [Method::GET, Method::PUT, Method::POST] {
449			for body in ["{", " \t\r\n"] {
450				let request = request(method.clone(), body);
451				let error = parse_json(&request, TypeId::of::<()>(), Scheme::ServerSignatures)
452					.unwrap_err();
453
454				assert_eq!(error.status_code(), StatusCode::BAD_REQUEST);
455				assert_eq!(error.kind(), ErrorKind::NotJson);
456			}
457		}
458	}
459
460	fn request(method: Method, body: &'static str) -> Request {
461		let (parts, ()) = HttpRequest::builder()
462			.method(method)
463			.uri("/")
464			.body(())
465			.unwrap()
466			.into_parts();
467
468		let query = QueryParams {
469			access_token: None,
470			user_id: None,
471			device_id: None,
472			msc3202_device_id: None,
473		};
474
475		Request {
476			cookie: CookieJar::default(),
477			path: Path(PathParams::new()),
478			query,
479			body: Bytes::from_static(body.as_bytes()),
480			parts,
481		}
482	}
483}