tuwunel_api/router/
request.rs1use std::str;
2
3use axum::{
4 RequestExt, RequestPartsExt,
5 body::{Body, to_bytes},
6 extract::Path,
7};
8use axum_extra::extract::cookie::CookieJar;
9use bytes::Bytes;
10use http::request::Parts;
11use serde::Deserialize;
12use tuwunel_core::{Result, err, smallstr::SmallString, smallvec::SmallVec};
13use tuwunel_service::Services;
14
15#[derive(Debug, Deserialize)]
16pub(super) struct QueryParams {
17 pub(super) access_token: Option<String>,
18
19 pub(super) user_id: Option<UserId>,
20
21 pub(super) device_id: Option<DeviceId>,
22
23 #[serde(rename = "org.matrix.msc3202.device_id")]
24 pub(super) msc3202_device_id: Option<DeviceId>,
25}
26
27impl QueryParams {
28 pub(super) fn device_id(&self) -> Option<&str> {
29 self.device_id
30 .as_deref()
31 .or(self.msc3202_device_id.as_deref())
32 }
33}
34
35pub(super) type UserId = SmallString<[u8; 48]>;
36pub(super) type DeviceId = SmallString<[u8; 24]>;
37
38#[derive(Debug)]
39pub(super) struct Request {
40 pub(super) cookie: CookieJar,
41 pub(super) path: Path<PathParams>,
42 pub(super) query: QueryParams,
43 pub(super) body: Bytes,
44 pub(super) parts: Parts,
45}
46
47pub(super) type PathParams = SmallVec<[PathParam; 8]>;
48pub(super) type PathParam = SmallString<[u8; 32]>;
49
50#[tracing::instrument(
51 name = "parse",
52 level = "trace",
53 skip_all,
54 err(level = "debug")
55)]
56pub(super) async fn from(services: &Services, request: http::Request<Body>) -> Result<Request> {
57 let limited = request.with_limited_body();
58 let (mut parts, body) = limited.into_parts();
59 let path: Path<PathParams> = parts.extract().await?;
60
61 from_parts(services, parts, body, path).await
62}
63
64pub(super) async fn from_parts(
68 services: &Services,
69 parts: Parts,
70 body: Body,
71 path: Path<PathParams>,
72) -> Result<Request> {
73 let cookie = CookieJar::from_headers(&parts.headers);
74
75 let query = parts.uri.query().unwrap_or_default();
76 let query = serde_html_form::from_str(query)
77 .map_err(|e| err!(Request(Unknown("Failed to read query parameters: {e}"))))?;
78
79 let body = read_body(services, body).await?;
80
81 Ok(Request { cookie, path, query, body, parts })
82}
83
84#[tracing::instrument(level = "trace", skip_all, err(level = "debug"))]
88pub async fn read_body(services: &Services, body: Body) -> Result<Bytes> {
89 to_bytes(body, services.server.config.http.max_request_size)
90 .await
91 .map_err(|e| err!(Request(TooLarge("Request body too large: {e}"))))
92}