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#[derive(Debug)]
39pub struct Args<T, const ADMIN: bool = false> {
40 pub body: T,
42
43 pub cookie: CookieJar,
45
46 pub origin: Option<OwnedServerName>,
48
49 pub sender_user: Option<OwnedUserId>,
51
52 pub sender_device: Option<OwnedDeviceId>,
54
55 pub appservice_info: Option<RegistrationInfo>,
57
58 pub json_body: Option<CanonicalJsonValue>,
60
61 pub rate_limit_ip: Result<IpAddr, &'static str>,
63}
64
65pub type ArgsAdmin<T> = Args<T, true>;
69
70#[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#[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#[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
185pub(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
232fn takes_raw_body(route: TypeId) -> bool {
238 route == TypeId::of::<UploadRequest>() || route == TypeId::of::<AsyncUploadRequest>()
239}
240
241async 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
259fn 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
303fn 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
341pub(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
352fn 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
366fn names_param_errors(route: TypeId) -> bool {
370 route == TypeId::of::<IsJoinedRequest>() || route == TypeId::of::<FedProxyRequest>()
371}
372
373fn 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}