From 667afedd24d40db1d63fa052dbd55e872b493225 Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Sat, 26 Apr 2025 23:50:03 +0000 Subject: [PATCH] Macroize various remaining Error constructions. Signed-off-by: Jason Volk --- src/api/client/account.rs | 16 +-- src/api/client/openid.rs | 13 +-- src/api/client/profile.rs | 15 ++- src/api/client/push.rs | 6 +- src/api/client/report.rs | 32 ++---- src/api/client/room/aliases.rs | 9 +- src/api/client/room/create.rs | 100 ++++++++---------- src/api/server/invite.rs | 2 +- .../rooms/event_handler/handle_outlier_pdu.rs | 10 +- 9 files changed, 78 insertions(+), 125 deletions(-) diff --git a/src/api/client/account.rs b/src/api/client/account.rs index 27d93bef..14bbcf98 100644 --- a/src/api/client/account.rs +++ b/src/api/client/account.rs @@ -13,22 +13,14 @@ use conduwuit_service::Services; use futures::{FutureExt, StreamExt}; use register::RegistrationKind; use ruma::{ - OwnedRoomId, UserId, api::client::{ account::{ - ThirdPartyIdRemovalStatus, change_password, check_registration_token_validity, - deactivate, get_3pids, get_username_availability, - register::{self, LoginType}, - request_3pid_management_token_via_email, request_3pid_management_token_via_msisdn, - whoami, + change_password, check_registration_token_validity, deactivate, get_3pids, get_username_availability, register::{self, LoginType}, request_3pid_management_token_via_email, request_3pid_management_token_via_msisdn, whoami, ThirdPartyIdRemovalStatus }, uiaa::{AuthFlow, AuthType, UiaaInfo}, - }, - events::{ - GlobalAccountDataEventType, StateEventType, - room::power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent}, - }, - push, + }, events::{ + room::{message::RoomMessageEventContent, power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent}}, GlobalAccountDataEventType, StateEventType + }, push, OwnedRoomId, UserId }; use super::{DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH, join_room_by_id_helper}; diff --git a/src/api/client/openid.rs b/src/api/client/openid.rs index e27b3ab8..0390b4b3 100644 --- a/src/api/client/openid.rs +++ b/src/api/client/openid.rs @@ -1,11 +1,8 @@ use std::time::Duration; use axum::extract::State; -use conduwuit::{Error, Result, utils}; -use ruma::{ - api::client::{account, error::ErrorKind}, - authentication::TokenType, -}; +use conduwuit::{Err, Result, utils}; +use ruma::{api::client::account, authentication::TokenType}; use super::TOKEN_LENGTH; use crate::Ruma; @@ -22,14 +19,12 @@ pub(crate) async fn create_openid_token_route( let sender_user = body.sender_user(); if sender_user != body.user_id { - return Err(Error::BadRequest( - ErrorKind::InvalidParam, + return Err!(Request(InvalidParam( "Not allowed to request OpenID tokens on behalf of other users", - )); + ))); } let access_token = utils::random_string(TOKEN_LENGTH); - let expires_in = services .users .create_openid_token(&body.user_id, &access_token)?; diff --git a/src/api/client/profile.rs b/src/api/client/profile.rs index 76b5dc6d..6efad64e 100644 --- a/src/api/client/profile.rs +++ b/src/api/client/profile.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; use axum::extract::State; use conduwuit::{ - Err, Error, Result, + Err, Result, matrix::pdu::PduBuilder, utils::{IterStream, stream::TryIgnore}, warn, @@ -12,11 +12,8 @@ use futures::{StreamExt, TryStreamExt, future::join3}; use ruma::{ OwnedMxcUri, OwnedRoomId, UserId, api::{ - client::{ - error::ErrorKind, - profile::{ - get_avatar_url, get_display_name, get_profile, set_avatar_url, set_display_name, - }, + client::profile::{ + get_avatar_url, get_display_name, get_profile, set_avatar_url, set_display_name, }, federation, }, @@ -110,7 +107,7 @@ pub(crate) async fn get_displayname_route( if !services.users.exists(&body.user_id).await { // Return 404 if this user doesn't exist and we couldn't fetch it over // federation - return Err(Error::BadRequest(ErrorKind::NotFound, "Profile was not found.")); + return Err!(Request(NotFound("Profile was not found."))); } Ok(get_display_name::v3::Response { @@ -214,7 +211,7 @@ pub(crate) async fn get_avatar_url_route( if !services.users.exists(&body.user_id).await { // Return 404 if this user doesn't exist and we couldn't fetch it over // federation - return Err(Error::BadRequest(ErrorKind::NotFound, "Profile was not found.")); + return Err!(Request(NotFound("Profile was not found."))); } Ok(get_avatar_url::v3::Response { @@ -287,7 +284,7 @@ pub(crate) async fn get_profile_route( if !services.users.exists(&body.user_id).await { // Return 404 if this user doesn't exist and we couldn't fetch it over // federation - return Err(Error::BadRequest(ErrorKind::NotFound, "Profile was not found.")); + return Err!(Request(NotFound("Profile was not found."))); } let mut custom_profile_fields: BTreeMap = services diff --git a/src/api/client/push.rs b/src/api/client/push.rs index 74e29422..d8d84ec7 100644 --- a/src/api/client/push.rs +++ b/src/api/client/push.rs @@ -218,7 +218,7 @@ pub(crate) async fn get_pushrule_route( if let Some(rule) = rule { Ok(get_pushrule::v3::Response { rule }) } else { - Err(Error::BadRequest(ErrorKind::NotFound, "Push rule not found.")) + Err!(Request(NotFound("Push rule not found."))) } } @@ -333,7 +333,7 @@ pub(crate) async fn set_pushrule_actions_route( .set_actions(body.kind.clone(), &body.rule_id, body.actions.clone()) .is_err() { - return Err(Error::BadRequest(ErrorKind::NotFound, "Push rule not found.")); + return Err!(Request(NotFound("Push rule not found."))); } let ty = GlobalAccountDataEventType::PushRules; @@ -400,7 +400,7 @@ pub(crate) async fn set_pushrule_enabled_route( .set_enabled(body.kind.clone(), &body.rule_id, body.enabled) .is_err() { - return Err(Error::BadRequest(ErrorKind::NotFound, "Push rule not found.")); + return Err!(Request(NotFound("Push rule not found."))); } let ty = GlobalAccountDataEventType::PushRules; diff --git a/src/api/client/report.rs b/src/api/client/report.rs index 8ece3ab1..1019b358 100644 --- a/src/api/client/report.rs +++ b/src/api/client/report.rs @@ -2,7 +2,7 @@ use std::{fmt::Write as _, ops::Mul, time::Duration}; use axum::extract::State; use axum_client_ip::InsecureClientIp; -use conduwuit::{Err, Error, Result, debug_info, info, matrix::pdu::PduEvent, utils::ReadyExt}; +use conduwuit::{Err, Result, debug_info, info, matrix::pdu::PduEvent, utils::ReadyExt}; use conduwuit_service::Services; use rand::Rng; use ruma::{ @@ -44,9 +44,8 @@ pub(crate) async fn report_room_route( } if body.reason.as_ref().is_some_and(|s| s.len() > 750) { - return Err(Error::BadRequest( - ErrorKind::InvalidParam, - "Reason too long, should be 750 characters or fewer", + return Err!(Request( + InvalidParam("Reason too long, should be 750 characters or fewer",) )); } @@ -149,9 +148,8 @@ pub(crate) async fn report_user_route( } if body.reason.as_ref().is_some_and(|s| s.len() > 750) { - return Err(Error::BadRequest( - ErrorKind::InvalidParam, - "Reason too long, should be 750 characters or fewer", + return Err!(Request( + InvalidParam("Reason too long, should be 750 characters or fewer",) )); } @@ -204,23 +202,16 @@ async fn is_event_report_valid( ); if room_id != pdu.room_id { - return Err(Error::BadRequest( - ErrorKind::NotFound, - "Event ID does not belong to the reported room", - )); + return Err!(Request(NotFound("Event ID does not belong to the reported room",))); } if score.is_some_and(|s| s > int!(0) || s < int!(-100)) { - return Err(Error::BadRequest( - ErrorKind::InvalidParam, - "Invalid score, must be within 0 to -100", - )); + return Err!(Request(InvalidParam("Invalid score, must be within 0 to -100",))); } if reason.as_ref().is_some_and(|s| s.len() > 750) { - return Err(Error::BadRequest( - ErrorKind::InvalidParam, - "Reason too long, should be 750 characters or fewer", + return Err!(Request( + InvalidParam("Reason too long, should be 750 characters or fewer",) )); } @@ -231,10 +222,7 @@ async fn is_event_report_valid( .ready_any(|user_id| user_id == sender_user) .await { - return Err(Error::BadRequest( - ErrorKind::NotFound, - "You are not in the room you are reporting.", - )); + return Err!(Request(NotFound("You are not in the room you are reporting.",))); } Ok(()) diff --git a/src/api/client/room/aliases.rs b/src/api/client/room/aliases.rs index a944971c..0b072b74 100644 --- a/src/api/client/room/aliases.rs +++ b/src/api/client/room/aliases.rs @@ -1,7 +1,7 @@ use axum::extract::State; -use conduwuit::{Error, Result}; +use conduwuit::{Err, Result}; use futures::StreamExt; -use ruma::api::client::{error::ErrorKind, room::aliases}; +use ruma::api::client::room::aliases; use crate::Ruma; @@ -23,10 +23,7 @@ pub(crate) async fn get_room_aliases_route( .user_can_see_state_events(sender_user, &body.room_id) .await { - return Err(Error::BadRequest( - ErrorKind::forbidden(), - "You don't have permission to view this room.", - )); + return Err!(Request(Forbidden("You don't have permission to view this room.",))); } Ok(aliases::v3::Response { diff --git a/src/api/client/room/create.rs b/src/api/client/room/create.rs index 8b93fcfd..238691d1 100644 --- a/src/api/client/room/create.rs +++ b/src/api/client/room/create.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; use axum::extract::State; use conduwuit::{ - Err, Error, Result, debug_info, debug_warn, err, error, info, + Err, Result, debug_info, debug_warn, err, info, matrix::{StateKey, pdu::PduBuilder}, warn, }; @@ -10,10 +10,7 @@ use conduwuit_service::{Services, appservice::RegistrationInfo}; use futures::FutureExt; use ruma::{ CanonicalJsonObject, Int, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, RoomId, RoomVersionId, - api::client::{ - error::ErrorKind, - room::{self, create_room}, - }, + api::client::room::{self, create_room}, events::{ TimelineEventType, room::{ @@ -64,10 +61,7 @@ pub(crate) async fn create_room_route( && body.appservice_info.is_none() && !services.users.is_admin(sender_user).await { - return Err(Error::BadRequest( - ErrorKind::forbidden(), - "Room creation has been disabled.", - )); + return Err!(Request(Forbidden("Room creation has been disabled.",))); } if services.users.is_suspended(sender_user).await? { @@ -81,10 +75,7 @@ pub(crate) async fn create_room_route( // check if room ID doesn't already exist instead of erroring on auth check if services.rooms.short.get_shortroomid(&room_id).await.is_ok() { - return Err(Error::BadRequest( - ErrorKind::RoomInUse, - "Room with that custom room ID already exists", - )); + return Err!(Request(RoomInUse("Room with that custom room ID already exists",))); } if body.visibility == room::Visibility::Public @@ -127,10 +118,9 @@ pub(crate) async fn create_room_route( if services.server.supported_room_version(&room_version) { room_version } else { - return Err(Error::BadRequest( - ErrorKind::UnsupportedRoomVersion, - "This server does not support that room version.", - )); + return Err!(Request(UnsupportedRoomVersion( + "This server does not support that room version." + ))); }, | None => services.server.config.default_room_version.clone(), }; @@ -142,16 +132,17 @@ pub(crate) async fn create_room_route( let mut content = content .deserialize_as::() .map_err(|e| { - error!("Failed to deserialise content as canonical JSON: {}", e); - Error::bad_database("Failed to deserialise content as canonical JSON.") + err!(Request(BadJson(error!( + "Failed to deserialise content as canonical JSON: {e}" + )))) })?; + match room_version { | V1 | V2 | V3 | V4 | V5 | V6 | V7 | V8 | V9 | V10 => { content.insert( "creator".into(), json!(&sender_user).try_into().map_err(|e| { - info!("Invalid creation content: {e}"); - Error::BadRequest(ErrorKind::BadJson, "Invalid creation content") + err!(Request(BadJson(debug_error!("Invalid creation content: {e}")))) })?, ); }, @@ -161,9 +152,9 @@ pub(crate) async fn create_room_route( } content.insert( "room_version".into(), - json!(room_version.as_str()).try_into().map_err(|_| { - Error::BadRequest(ErrorKind::BadJson, "Invalid creation content") - })?, + json!(room_version.as_str()) + .try_into() + .map_err(|e| err!(Request(BadJson("Invalid creation content: {e}"))))?, ); content }, @@ -345,8 +336,7 @@ pub(crate) async fn create_room_route( // 6. Events listed in initial_state for event in &body.initial_state { let mut pdu_builder = event.deserialize_as::().map_err(|e| { - warn!("Invalid initial state event: {:?}", e); - Error::BadRequest(ErrorKind::InvalidParam, "Invalid initial state event.") + err!(Request(InvalidParam(warn!("Invalid initial state event: {e:?}")))) })?; debug_info!("Room creation initial state event: {event:?}"); @@ -355,7 +345,7 @@ pub(crate) async fn create_room_route( // state event in there with the content of literally `{}` (not null or empty // string), let's just skip it over and warn. if pdu_builder.content.get().eq("{}") { - info!("skipping empty initial state event with content of `{{}}`: {event:?}"); + debug_warn!("skipping empty initial state event with content of `{{}}`: {event:?}"); debug_warn!("content: {}", pdu_builder.content.get()); continue; } @@ -502,9 +492,7 @@ fn default_power_levels_content( if let Some(power_level_content_override) = power_level_content_override { let json: JsonObject = serde_json::from_str(power_level_content_override.json().get()) - .map_err(|_| { - Error::BadRequest(ErrorKind::BadJson, "Invalid power_level_content_override.") - })?; + .map_err(|e| err!(Request(BadJson("Invalid power_level_content_override: {e:?}"))))?; for (key, value) in json { power_levels_content[key] = value; @@ -522,16 +510,14 @@ async fn room_alias_check( ) -> Result { // Basic checks on the room alias validity if room_alias_name.contains(':') { - return Err(Error::BadRequest( - ErrorKind::InvalidParam, + return Err!(Request(InvalidParam( "Room alias contained `:` which is not allowed. Please note that this expects a \ localpart, not the full room alias.", - )); + ))); } else if room_alias_name.contains(char::is_whitespace) { - return Err(Error::BadRequest( - ErrorKind::InvalidParam, + return Err!(Request(InvalidParam( "Room alias contained spaces which is not a valid room alias.", - )); + ))); } // check if room alias is forbidden @@ -540,7 +526,7 @@ async fn room_alias_check( .forbidden_alias_names() .is_match(room_alias_name) { - return Err(Error::BadRequest(ErrorKind::Unknown, "Room alias name is forbidden.")); + return Err!(Request(Unknown("Room alias name is forbidden."))); } let server_name = services.globals.server_name(); @@ -560,25 +546,19 @@ async fn room_alias_check( .await .is_ok() { - return Err(Error::BadRequest(ErrorKind::RoomInUse, "Room alias already exists.")); + return Err!(Request(RoomInUse("Room alias already exists."))); } if let Some(info) = appservice_info { if !info.aliases.is_match(full_room_alias.as_str()) { - return Err(Error::BadRequest( - ErrorKind::Exclusive, - "Room alias is not in namespace.", - )); + return Err!(Request(Exclusive("Room alias is not in namespace."))); } } else if services .appservice .is_exclusive_alias(&full_room_alias) .await { - return Err(Error::BadRequest( - ErrorKind::Exclusive, - "Room alias reserved by appservice.", - )); + return Err!(Request(Exclusive("Room alias reserved by appservice.",))); } debug_info!("Full room alias: {full_room_alias}"); @@ -594,24 +574,33 @@ fn custom_room_id_check(services: &Services, custom_room_id: &str) -> Result Result( v.insert(auth_event); }, | hash_map::Entry::Occupied(_) => { - return Err(Error::BadRequest( - ErrorKind::InvalidParam, + return Err!(Request(InvalidParam( "Auth event's type and state_key combination exists multiple times.", - )); + ))); }, } }