Files
continuwuity/src/api/router/args.rs
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

113 lines
3.2 KiB
Rust
Raw Normal View History

2026-04-13 16:20:47 -04:00
use std::ops::Deref;
2026-04-13 16:20:47 -04:00
use axum::{
RequestExt, RequestPartsExt,
body::Body,
extract::{FromRequest, Path, Query},
};
2026-04-13 16:20:47 -04:00
use conduwuit::{Error, Result, err};
2026-08-25 05:04:08 +00:00
use ruma::{
CanonicalJsonObject,
2026-08-26 13:15:32 -04:00
api::{IncomingRequest, IncomingRequestExt, auth_scheme::AuthScheme},
2026-08-25 05:04:08 +00:00
};
2026-04-13 16:20:47 -04:00
use serde::Deserialize;
2024-03-05 19:48:54 -05:00
use crate::{State, router::auth::CheckAuth};
2026-04-13 16:20:47 -04:00
/// Query parameters needed to authenticate requests
#[derive(Deserialize)]
pub(crate) struct AuthQueryParams {
2026-04-13 16:20:47 -04:00
pub(super) user_id: Option<String>,
pub(super) device_id: Option<String>,
#[serde(rename = "org.matrix.msc3202.device_id")]
pub(super) legacy_device_id: Option<String>,
2026-04-13 16:20:47 -04:00
}
2020-02-15 22:42:21 +01:00
2022-01-20 11:51:31 +01:00
/// Extractor for Ruma request structs
pub(crate) struct Args<R: IncomingRequest<Authentication: CheckAuth> + Send + Sync + 'static> {
/// Request struct body
pub(crate) body: R,
/// Parsed JSON body. None when body is not JSON.
2026-04-22 10:41:01 -04:00
pub(crate) json_body: Option<CanonicalJsonObject>,
/// Identity of the requesting entity
pub(crate) identity: <R::Authentication as CheckAuth>::Identity,
}
impl<R> Deref for Args<R>
where
R: IncomingRequest<Authentication: CheckAuth> + Send + Sync + 'static,
{
type Target = R;
fn deref(&self) -> &Self::Target { &self.body }
}
2026-04-13 16:20:47 -04:00
impl<R> FromRequest<State, Body> for Args<R>
where
2026-04-13 16:20:47 -04:00
R: IncomingRequest<Authentication: CheckAuth> + Send + Sync + 'static,
{
type Rejection = Error;
async fn from_request(
request: hyper::Request<Body>,
services: &State,
) -> Result<Self, Self::Rejection> {
2026-04-13 16:20:47 -04:00
let limited = request.with_limited_body();
let (mut parts, body) = limited.into_parts();
// Read the body
let body = {
let max_body_size = services.server.config.max_request_size;
// Check if the Content-Length header is present and valid, saves us
// streaming the response into memory
if let Some(content_length) = parts.headers.get(http::header::CONTENT_LENGTH) {
if let Ok(content_length) = content_length
.to_str()
.map(|s| s.parse::<usize>().unwrap_or_default())
{
if content_length > max_body_size {
return Err(err!(Request(TooLarge("Request body too large"))));
}
}
}
axum::body::to_bytes(body, max_body_size)
.await
.map_err(|e| err!(Request(TooLarge("Request body too large: {e}"))))?
};
// Make a JSON copy of the body for use in handlers
2026-04-22 10:41:01 -04:00
let json_body = serde_json::from_slice::<CanonicalJsonObject>(&body).ok();
2026-04-13 16:20:47 -04:00
// Extract the query parameters and path
let Path(path): Path<Vec<String>> = parts.extract().await?;
2026-08-25 05:04:08 +00:00
let borrowed_path: Vec<_> = path.iter().map(String::as_str).collect();
2026-04-13 16:20:47 -04:00
let Query(auth_query): Query<AuthQueryParams> = parts.extract().await?;
// Assemble a new request from the read body and parts
2026-08-25 05:04:08 +00:00
let request = hyper::Request::from_parts(parts, body.as_ref());
2026-04-13 16:20:47 -04:00
// Check authentication
2026-08-26 13:15:32 -04:00
let authentication =
R::Authentication::extract_authentication(&request).map_err(|err| {
err!(Request(Unauthorized(warn!(
path = request.uri().path(),
err = err.into(),
"Failed to extract authentication"
))))
})?;
let identity =
R::Authentication::check::<R>(services, &request, authentication, auth_query).await?;
2026-04-13 16:20:47 -04:00
// Deserialize the body
2026-08-25 05:04:08 +00:00
let body = R::try_from_http_request(request, &borrowed_path)
2026-04-13 16:20:47 -04:00
.map_err(|e| err!(Request(BadJson(debug_warn!("{e}")))))?;
2026-08-26 13:15:32 -04:00
Ok(Self { body, json_body, identity })
}
2020-03-28 18:50:02 +01:00
}