apply new rustfmt.toml changes, fix some clippy lints

Signed-off-by: strawberry <strawberry@puppygock.gay>
This commit is contained in:
strawberry 2024-12-15 00:05:47 -05:00
parent 0317cc8cc5
commit 77e0b76408
No known key found for this signature in database
296 changed files with 7147 additions and 4300 deletions

View file

@ -4,8 +4,8 @@ use axum::{async_trait, body::Body, extract::FromRequest};
use bytes::{BufMut, Bytes, BytesMut};
use conduwuit::{debug, debug_warn, err, trace, utils::string::EMPTY, Error, Result};
use ruma::{
api::IncomingRequest, CanonicalJsonObject, CanonicalJsonValue, DeviceId, OwnedDeviceId, OwnedServerName,
OwnedUserId, ServerName, UserId,
api::IncomingRequest, CanonicalJsonObject, CanonicalJsonValue, DeviceId, OwnedDeviceId,
OwnedServerName, OwnedUserId, ServerName, UserId,
};
use service::Services;
@ -43,7 +43,9 @@ where
T: IncomingRequest + Send + Sync + 'static,
{
#[inline]
pub(crate) fn sender(&self) -> (&UserId, &DeviceId) { (self.sender_user(), self.sender_device()) }
pub(crate) fn sender(&self) -> (&UserId, &DeviceId) {
(self.sender_user(), self.sender_device())
}
#[inline]
pub(crate) fn sender_user(&self) -> &UserId {
@ -83,7 +85,10 @@ where
{
type Rejection = Error;
async fn from_request(request: hyper::Request<Body>, services: &State) -> Result<Self, Self::Rejection> {
async fn from_request(
request: hyper::Request<Body>,
services: &State,
) -> Result<Self, Self::Rejection> {
let mut request = request::from(services, request).await?;
let mut json_body = serde_json::from_slice::<CanonicalJsonValue>(&request.body).ok();
@ -96,7 +101,10 @@ where
&& !request.parts.uri.path().contains("/media/")
{
trace!("json_body from_request: {:?}", json_body.clone());
debug_warn!("received a POST request with an empty body, defaulting/assuming to {{}} like Synapse does");
debug_warn!(
"received a POST request with an empty body, defaulting/assuming to {{}} like \
Synapse does"
);
json_body = Some(CanonicalJsonValue::Object(CanonicalJsonObject::new()));
}
let auth = auth::auth(services, &mut request, json_body.as_ref(), &T::METADATA).await?;
@ -112,14 +120,18 @@ where
}
fn make_body<T>(
services: &Services, request: &mut Request, json_body: Option<&mut CanonicalJsonValue>, auth: &Auth,
services: &Services,
request: &mut Request,
json_body: Option<&mut CanonicalJsonValue>,
auth: &Auth,
) -> Result<T>
where
T: IncomingRequest,
{
let body = take_body(services, request, json_body, auth);
let http_request = into_http_request(request, body);
T::try_from_http_request(http_request, &request.path).map_err(|e| err!(Request(BadJson(debug_warn!("{e}")))))
T::try_from_http_request(http_request, &request.path)
.map_err(|e| err!(Request(BadJson(debug_warn!("{e}")))))
}
fn into_http_request(request: &Request, body: Bytes) -> hyper::Request<Bytes> {
@ -141,7 +153,10 @@ fn into_http_request(request: &Request, body: Bytes) -> hyper::Request<Bytes> {
#[allow(clippy::needless_pass_by_value)]
fn take_body(
services: &Services, request: &mut Request, json_body: Option<&mut CanonicalJsonValue>, auth: &Auth,
services: &Services,
request: &mut Request,
json_body: Option<&mut CanonicalJsonValue>,
auth: &Auth,
) -> Bytes {
let Some(CanonicalJsonValue::Object(json_body)) = json_body else {
return mem::take(&mut request.body);

View file

@ -10,7 +10,9 @@ use ruma::{
client::{
directory::get_public_rooms,
error::ErrorKind,
profile::{get_avatar_url, get_display_name, get_profile, get_profile_key, get_timezone_key},
profile::{
get_avatar_url, get_display_name, get_profile, get_profile_key, get_timezone_key,
},
voip::get_turn_server_info,
},
federation::openid::get_openid_userinfo,
@ -42,12 +44,15 @@ pub(super) struct Auth {
}
pub(super) async fn auth(
services: &Services, request: &mut Request, json_body: Option<&CanonicalJsonValue>, metadata: &Metadata,
services: &Services,
request: &mut Request,
json_body: Option<&CanonicalJsonValue>,
metadata: &Metadata,
) -> Result<Auth> {
let bearer: Option<TypedHeader<Authorization<Bearer>>> = request.parts.extract().await?;
let token = match &bearer {
Some(TypedHeader(Authorization(bearer))) => Some(bearer.token()),
None => request.query.access_token.as_deref(),
| Some(TypedHeader(Authorization(bearer))) => Some(bearer.token()),
| None => request.query.access_token.as_deref(),
};
let token = if let Some(token) = token {
@ -64,56 +69,64 @@ pub(super) async fn auth(
if metadata.authentication == AuthScheme::None {
match metadata {
&get_public_rooms::v3::Request::METADATA => {
| &get_public_rooms::v3::Request::METADATA => {
if !services
.globals
.config
.allow_public_room_directory_without_auth
{
match token {
Token::Appservice(_) | Token::User(_) => {
| Token::Appservice(_) | Token::User(_) => {
// we should have validated the token above
// already
},
Token::None | Token::Invalid => {
return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing or invalid access token."));
| Token::None | Token::Invalid => {
return Err(Error::BadRequest(
ErrorKind::MissingToken,
"Missing or invalid access token.",
));
},
}
}
},
&get_profile::v3::Request::METADATA
| &get_profile::v3::Request::METADATA
| &get_profile_key::unstable::Request::METADATA
| &get_display_name::v3::Request::METADATA
| &get_avatar_url::v3::Request::METADATA
| &get_timezone_key::unstable::Request::METADATA => {
if services.globals.config.require_auth_for_profile_requests {
match token {
Token::Appservice(_) | Token::User(_) => {
| Token::Appservice(_) | Token::User(_) => {
// we should have validated the token above
// already
},
Token::None | Token::Invalid => {
return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing or invalid access token."));
| Token::None | Token::Invalid => {
return Err(Error::BadRequest(
ErrorKind::MissingToken,
"Missing or invalid access token.",
));
},
}
}
},
_ => {},
| _ => {},
};
}
match (metadata.authentication, token) {
(AuthScheme::AccessToken, Token::Appservice(info)) => Ok(auth_appservice(services, request, info).await?),
(AuthScheme::None | AuthScheme::AccessTokenOptional | AuthScheme::AppserviceToken, Token::Appservice(info)) => {
Ok(Auth {
origin: None,
sender_user: None,
sender_device: None,
appservice_info: Some(*info),
})
},
(AuthScheme::AccessToken, Token::None) => match metadata {
&get_turn_server_info::v3::Request::METADATA => {
| (AuthScheme::AccessToken, Token::Appservice(info)) =>
Ok(auth_appservice(services, request, info).await?),
| (
AuthScheme::None | AuthScheme::AccessTokenOptional | AuthScheme::AppserviceToken,
Token::Appservice(info),
) => Ok(Auth {
origin: None,
sender_user: None,
sender_device: None,
appservice_info: Some(*info),
}),
| (AuthScheme::AccessToken, Token::None) => match metadata {
| &get_turn_server_info::v3::Request::METADATA => {
if services.globals.config.turn_allow_guests {
Ok(Auth {
origin: None,
@ -125,9 +138,9 @@ pub(super) async fn auth(
Err(Error::BadRequest(ErrorKind::MissingToken, "Missing access token."))
}
},
_ => Err(Error::BadRequest(ErrorKind::MissingToken, "Missing access token.")),
| _ => Err(Error::BadRequest(ErrorKind::MissingToken, "Missing access token.")),
},
(
| (
AuthScheme::AccessToken | AuthScheme::AccessTokenOptional | AuthScheme::None,
Token::User((user_id, device_id)),
) => Ok(Auth {
@ -136,26 +149,33 @@ pub(super) async fn auth(
sender_device: Some(device_id),
appservice_info: None,
}),
(AuthScheme::ServerSignatures, Token::None) => Ok(auth_server(services, request, json_body).await?),
(AuthScheme::None | AuthScheme::AppserviceToken | AuthScheme::AccessTokenOptional, Token::None) => Ok(Auth {
| (AuthScheme::ServerSignatures, Token::None) =>
Ok(auth_server(services, request, json_body).await?),
| (
AuthScheme::None | AuthScheme::AppserviceToken | AuthScheme::AccessTokenOptional,
Token::None,
) => Ok(Auth {
sender_user: None,
sender_device: None,
origin: None,
appservice_info: None,
}),
(AuthScheme::ServerSignatures, Token::Appservice(_) | Token::User(_)) => Err(Error::BadRequest(
ErrorKind::Unauthorized,
"Only server signatures should be used on this endpoint.",
)),
(AuthScheme::AppserviceToken, Token::User(_)) => Err(Error::BadRequest(
| (AuthScheme::ServerSignatures, Token::Appservice(_) | Token::User(_)) =>
Err(Error::BadRequest(
ErrorKind::Unauthorized,
"Only server signatures should be used on this endpoint.",
)),
| (AuthScheme::AppserviceToken, Token::User(_)) => Err(Error::BadRequest(
ErrorKind::Unauthorized,
"Only appservice access tokens should be used on this endpoint.",
)),
(AuthScheme::None, Token::Invalid) => {
| (AuthScheme::None, Token::Invalid) => {
// OpenID federation endpoint uses a query param with the same name, drop this
// once query params for user auth are removed from the spec. This is
// required to make integration manager work.
if request.query.access_token.is_some() && metadata == &get_openid_userinfo::v1::Request::METADATA {
if request.query.access_token.is_some()
&& metadata == &get_openid_userinfo::v1::Request::METADATA
{
Ok(Auth {
origin: None,
sender_user: None,
@ -164,25 +184,29 @@ pub(super) async fn auth(
})
} else {
Err(Error::BadRequest(
ErrorKind::UnknownToken {
soft_logout: false,
},
ErrorKind::UnknownToken { soft_logout: false },
"Unknown access token.",
))
}
},
(_, Token::Invalid) => Err(Error::BadRequest(
ErrorKind::UnknownToken {
soft_logout: false,
},
| (_, Token::Invalid) => Err(Error::BadRequest(
ErrorKind::UnknownToken { soft_logout: false },
"Unknown access token.",
)),
}
}
async fn auth_appservice(services: &Services, request: &Request, info: Box<RegistrationInfo>) -> Result<Auth> {
let user_id_default =
|| UserId::parse_with_server_name(info.registration.sender_localpart.as_str(), services.globals.server_name());
async fn auth_appservice(
services: &Services,
request: &Request,
info: Box<RegistrationInfo>,
) -> Result<Auth> {
let user_id_default = || {
UserId::parse_with_server_name(
info.registration.sender_localpart.as_str(),
services.globals.server_name(),
)
};
let Ok(user_id) = request
.query
@ -205,7 +229,11 @@ async fn auth_appservice(services: &Services, request: &Request, info: Box<Regis
})
}
async fn auth_server(services: &Services, request: &mut Request, body: Option<&CanonicalJsonValue>) -> Result<Auth> {
async fn auth_server(
services: &Services,
request: &mut Request,
body: Option<&CanonicalJsonValue>,
) -> Result<Auth> {
type Member = (String, CanonicalJsonValue);
type Object = CanonicalJsonObject;
type Value = CanonicalJsonValue;
@ -222,7 +250,8 @@ async fn auth_server(services: &Services, request: &mut Request, body: Option<&C
.expect("all requests have a path")
.to_string();
let signature: [Member; 1] = [(x_matrix.key.as_str().into(), Value::String(x_matrix.sig.to_string()))];
let signature: [Member; 1] =
[(x_matrix.key.as_str().into(), Value::String(x_matrix.sig.to_string()))];
let signatures: [Member; 1] = [(origin.as_str().into(), Value::Object(signature.into()))];
@ -261,8 +290,8 @@ async fn auth_server(services: &Services, request: &mut Request, body: Option<&C
debug_error!("Failed to verify federation request from {origin}: {e}");
if request.parts.uri.to_string().contains('@') {
warn!(
"Request uri contained '@' character. Make sure your reverse proxy gives conduwuit the raw uri \
(apache: use nocanon)"
"Request uri contained '@' character. Make sure your reverse proxy gives \
conduwuit the raw uri (apache: use nocanon)"
);
}
@ -294,7 +323,9 @@ fn auth_server_checks(services: &Services, x_matrix: &XMatrix) -> Result<()> {
.forbidden_remote_server_names
.contains(origin)
{
return Err!(Request(Forbidden(debug_warn!("Federation requests from {origin} denied."))));
return Err!(Request(Forbidden(debug_warn!(
"Federation requests from {origin} denied."
))));
}
Ok(())
@ -307,9 +338,9 @@ async fn parse_x_matrix(request: &mut Request) -> Result<XMatrix> {
.await
.map_err(|e| {
let msg = match e.reason() {
TypedHeaderRejectionReason::Missing => "Missing Authorization header.",
TypedHeaderRejectionReason::Error(_) => "Invalid X-Matrix signatures.",
_ => "Unknown header-related error",
| TypedHeaderRejectionReason::Missing => "Missing Authorization header.",
| TypedHeaderRejectionReason::Error(_) => "Invalid X-Matrix signatures.",
| _ => "Unknown header-related error",
};
err!(Request(Forbidden(warn!("{msg}: {e}"))))

View file

@ -66,14 +66,14 @@ ruma_handler!(T1, T2, T3, T4);
const fn method_to_filter(method: &Method) -> MethodFilter {
match *method {
Method::DELETE => MethodFilter::DELETE,
Method::GET => MethodFilter::GET,
Method::HEAD => MethodFilter::HEAD,
Method::OPTIONS => MethodFilter::OPTIONS,
Method::PATCH => MethodFilter::PATCH,
Method::POST => MethodFilter::POST,
Method::PUT => MethodFilter::PUT,
Method::TRACE => MethodFilter::TRACE,
_ => panic!("Unsupported HTTP method"),
| Method::DELETE => MethodFilter::DELETE,
| Method::GET => MethodFilter::GET,
| Method::HEAD => MethodFilter::HEAD,
| Method::OPTIONS => MethodFilter::OPTIONS,
| Method::PATCH => MethodFilter::PATCH,
| Method::POST => MethodFilter::POST,
| Method::PUT => MethodFilter::PUT,
| Method::TRACE => MethodFilter::TRACE,
| _ => panic!("Unsupported HTTP method"),
}
}

View file

@ -20,14 +20,17 @@ pub(super) struct Request {
pub(super) parts: Parts,
}
pub(super) async fn from(services: &Services, request: hyper::Request<axum::body::Body>) -> Result<Request> {
pub(super) async fn from(
services: &Services,
request: hyper::Request<axum::body::Body>,
) -> Result<Request> {
let limited = request.with_limited_body();
let (mut parts, body) = limited.into_parts();
let path: Path<Vec<String>> = parts.extract().await?;
let query = parts.uri.query().unwrap_or_default();
let query =
serde_html_form::from_str(query).map_err(|e| err!(Request(Unknown("Failed to read query parameters: {e}"))))?;
let query = serde_html_form::from_str(query)
.map_err(|e| err!(Request(Unknown("Failed to read query parameters: {e}"))))?;
let max_body_size = services.globals.config.max_request_size;
@ -35,10 +38,5 @@ pub(super) async fn from(services: &Services, request: hyper::Request<axum::body
.await
.map_err(|e| err!(Request(TooLarge("Request body too large: {e}"))))?;
Ok(Request {
path,
query,
body,
parts,
})
Ok(Request { path, query, body, parts })
}

View file

@ -16,9 +16,7 @@ pub fn create(services: Arc<Services>) -> (State, Guard) {
services: Arc::into_raw(services.clone()),
};
let guard = Guard {
services,
};
let guard = Guard { services };
(state, guard)
}