chore: bump all dependencies

This commit is contained in:
Matthias Ahouansou 2024-04-07 20:46:18 +01:00
parent c45e52f45a
commit ba2a5a6115
No known key found for this signature in database
23 changed files with 975 additions and 704 deletions

1315
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -28,43 +28,24 @@ workspace = true
[dependencies] [dependencies]
# Web framework # Web framework
axum = { version = "0.6.18", default-features = false, features = [ axum = { version = "0.7", default-features = false, features = [
"form", "form",
"headers",
"http1", "http1",
"http2", "http2",
"json", "json",
"matched-path", "matched-path",
], optional = true } ], optional = true }
axum-server = { version = "0.5.1", features = ["tls-rustls"] } axum-extra = { version = "0.9", features = ["typed-header"] }
axum-server = { version = "0.6", features = ["tls-rustls"] }
tower = { version = "0.4.13", features = ["util"] } tower = { version = "0.4.13", features = ["util"] }
tower-http = { version = "0.4.1", features = [ tower-http = { version = "0.5", features = [
"add-extension", "add-extension",
"cors", "cors",
"sensitive-headers", "sensitive-headers",
"trace", "trace",
"util", "util",
] } ] }
tower-service = "0.3"
# Used for matrix spec type definitions and helpers
#ruma = { version = "0.4.0", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
ruma = { git = "https://github.com/ruma/ruma", rev = "c5f8137ba9741b2317313256b57e6e14b61fb419", features = [
"appservice-api-c",
"client-api",
"compat",
"federation-api",
"push-gateway-api-c",
"rand",
"ring-compat",
"server-util",
"state-res",
"unstable-exhaustive-types",
"unstable-msc2448",
"unstable-msc3575",
"unstable-unspecified",
] }
#ruma = { git = "https://github.com/timokoesters/ruma", rev = "4ec9c69bb7e09391add2382b3ebac97b6e8f4c64", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-msc3575", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified" ] }
#ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-msc3575", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified" ] }
# Async runtime and utilities # Async runtime and utilities
tokio = { version = "1.28.1", features = ["fs", "macros", "signal", "sync"] } tokio = { version = "1.28.1", features = ["fs", "macros", "signal", "sync"] }
@ -75,7 +56,7 @@ persy = { version = "1.4.4", optional = true, features = ["background_ops"] }
# Used for the http request / response body type for Ruma endpoints used with reqwest # Used for the http request / response body type for Ruma endpoints used with reqwest
bytes = "1.4.0" bytes = "1.4.0"
http = "0.2.9" http = "1"
# Used to find data directory for default db path # Used to find data directory for default db path
directories = "5" directories = "5"
# Used for ruma wrapper # Used for ruma wrapper
@ -89,8 +70,14 @@ rand = "0.8.5"
# Used to hash passwords # Used to hash passwords
rust-argon2 = "2" rust-argon2 = "2"
# Used to send requests # Used to send requests
hyper = "0.14.26" hyper = "1.1"
reqwest = { version = "0.11.18", default-features = false, features = [ hyper-util = { version = "0.1", features = [
"client",
"client-legacy",
"http1",
"http2",
] }
reqwest = { version = "0.12", default-features = false, features = [
"rustls-tls-native-roots", "rustls-tls-native-roots",
"socks", "socks",
] } ] }
@ -113,11 +100,13 @@ regex = "1.8.1"
# jwt jsonwebtokens # jwt jsonwebtokens
jsonwebtoken = "9.2.0" jsonwebtoken = "9.2.0"
# Performance measurements # Performance measurements
opentelemetry = { version = "0.18.0", features = ["rt-tokio"] } opentelemetry = "0.22"
opentelemetry-jaeger = { version = "0.17.0", features = ["rt-tokio"] } opentelemetry-jaeger-propagator = "0.1"
tracing = { version = "0.1.37", features = [] } opentelemetry-otlp = "0.15"
opentelemetry_sdk = { version = "0.22", features = ["rt-tokio"] }
tracing = "0.1.37"
tracing-flame = "0.2.0" tracing-flame = "0.2.0"
tracing-opentelemetry = "0.18.0" tracing-opentelemetry = "0.23"
tracing-subscriber = { version = "0.3.17", features = ["env-filter"] } tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }
lru-cache = "0.1.2" lru-cache = "0.1.2"
@ -158,6 +147,25 @@ tikv-jemallocator = { version = "0.5.0", features = [
sd-notify = { version = "0.4.1", optional = true } sd-notify = { version = "0.4.1", optional = true }
# Used for matrix spec type definitions and helpers
[dependencies.ruma]
features = [
"appservice-api-c",
"client-api",
"compat",
"federation-api",
"push-gateway-api-c",
"rand",
"ring-compat",
"server-util",
"state-res",
"unstable-exhaustive-types",
"unstable-msc2448",
"unstable-msc3575",
"unstable-unspecified",
]
git = "https://github.com/ruma/ruma"
[dependencies.rocksdb] [dependencies.rocksdb]
features = ["lz4", "multi-threaded-cf", "zstd"] features = ["lz4", "multi-threaded-cf", "zstd"]
optional = true optional = true

View file

@ -77,7 +77,7 @@ pub async fn get_register_available_route(
pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<register::v3::Response> { pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<register::v3::Response> {
if !services().globals.allow_registration().await && body.appservice_info.is_none() { if !services().globals.allow_registration().await && body.appservice_info.is_none() {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Registration has been disabled.", "Registration has been disabled.",
)); ));
} }

View file

@ -54,7 +54,7 @@ pub async fn get_context_route(
.user_can_see_event(sender_user, &room_id, &body.event_id)? .user_can_see_event(sender_user, &room_id, &body.event_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"You don't have permission to view this event.", "You don't have permission to view this event.",
)); ));
} }

View file

@ -451,7 +451,7 @@ pub async fn get_member_events_route(
.user_can_see_state_events(sender_user, &body.room_id)? .user_can_see_state_events(sender_user, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"You don't have permission to view this room.", "You don't have permission to view this room.",
)); ));
} }
@ -486,7 +486,7 @@ pub async fn joined_members_route(
.user_can_see_state_events(sender_user, &body.room_id)? .user_can_see_state_events(sender_user, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"You don't have permission to view this room.", "You don't have permission to view this room.",
)); ));
} }
@ -1314,7 +1314,7 @@ pub(crate) async fn invite_helper<'a>(
.is_joined(sender_user, room_id)? .is_joined(sender_user, room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"You don't have permission to view this room.", "You don't have permission to view this room.",
)); ));
} }

View file

@ -43,7 +43,7 @@ pub async fn send_message_event_route(
&& !services().globals.allow_encryption() && !services().globals.allow_encryption()
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Encryption has been disabled", "Encryption has been disabled",
)); ));
} }

View file

@ -72,7 +72,7 @@ pub async fn create_room_route(
&& !services().users.is_admin(sender_user)? && !services().users.is_admin(sender_user)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Room creation has been disabled.", "Room creation has been disabled.",
)); ));
} }
@ -522,7 +522,7 @@ pub async fn get_room_event_route(
&body.event_id, &body.event_id,
)? { )? {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"You don't have permission to view this event.", "You don't have permission to view this event.",
)); ));
} }
@ -551,7 +551,7 @@ pub async fn get_room_aliases_route(
.is_joined(sender_user, &body.room_id)? .is_joined(sender_user, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"You don't have permission to view this room.", "You don't have permission to view this room.",
)); ));
} }

View file

@ -43,7 +43,7 @@ pub async fn search_events_route(
.is_joined(sender_user, &room_id)? .is_joined(sender_user, &room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"You don't have permission to view this room.", "You don't have permission to view this room.",
)); ));
} }

View file

@ -63,7 +63,7 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
UserId::parse(user) UserId::parse(user)
} else { } else {
warn!("Bad login type: {:?}", &body.login_info); warn!("Bad login type: {:?}", &body.login_info);
return Err(Error::BadRequest(ErrorKind::Forbidden, "Bad login type.")); return Err(Error::BadRequest(ErrorKind::forbidden(), "Bad login type."));
} }
.map_err(|_| Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?; .map_err(|_| Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;
@ -78,7 +78,7 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
.users .users
.password_hash(&user_id)? .password_hash(&user_id)?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Wrong username or password.", "Wrong username or password.",
))?; ))?;
@ -93,7 +93,7 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
if !hash_matches { if !hash_matches {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Wrong username or password.", "Wrong username or password.",
)); ));
} }
@ -143,7 +143,7 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
UserId::parse(user) UserId::parse(user)
} else { } else {
warn!("Bad login type: {:?}", &body.login_info); warn!("Bad login type: {:?}", &body.login_info);
return Err(Error::BadRequest(ErrorKind::Forbidden, "Bad login type.")); return Err(Error::BadRequest(ErrorKind::forbidden(), "Bad login type."));
} }
.map_err(|_| Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?; .map_err(|_| Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;

View file

@ -54,7 +54,7 @@ pub async fn send_state_event_for_empty_key_route(
// Forbid m.room.encryption if encryption is disabled // Forbid m.room.encryption if encryption is disabled
if body.event_type == StateEventType::RoomEncryption && !services().globals.allow_encryption() { if body.event_type == StateEventType::RoomEncryption && !services().globals.allow_encryption() {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Encryption has been disabled", "Encryption has been disabled",
)); ));
} }
@ -88,7 +88,7 @@ pub async fn get_state_events_route(
.user_can_see_state_events(sender_user, &body.room_id)? .user_can_see_state_events(sender_user, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"You don't have permission to view the room state.", "You don't have permission to view the room state.",
)); ));
} }
@ -121,7 +121,7 @@ pub async fn get_state_events_for_key_route(
.user_can_see_state_events(sender_user, &body.room_id)? .user_can_see_state_events(sender_user, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"You don't have permission to view the room state.", "You don't have permission to view the room state.",
)); ));
} }
@ -160,7 +160,7 @@ pub async fn get_state_events_for_empty_key_route(
.user_can_see_state_events(sender_user, &body.room_id)? .user_can_see_state_events(sender_user, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"You don't have permission to view the room state.", "You don't have permission to view the room state.",
)); ));
} }
@ -214,7 +214,7 @@ async fn send_state_event_for_key_helper(
.is_none() .is_none()
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"You are only allowed to send canonical_alias \ "You are only allowed to send canonical_alias \
events when it's aliases already exists", events when it's aliases already exists",
)); ));

View file

@ -12,7 +12,7 @@ use ruma::{
Ephemeral, Filter, GlobalAccountData, InviteState, InvitedRoom, JoinedRoom, Ephemeral, Filter, GlobalAccountData, InviteState, InvitedRoom, JoinedRoom,
LeftRoom, Presence, RoomAccountData, RoomSummary, Rooms, State, Timeline, ToDevice, LeftRoom, Presence, RoomAccountData, RoomSummary, Rooms, State, Timeline, ToDevice,
}, },
v4::SlidingOp, v4::{SlidingOp, SlidingSyncRoomHero},
DeviceLists, UnreadNotificationsCount, DeviceLists, UnreadNotificationsCount,
}, },
uiaa::UiaaResponse, uiaa::UiaaResponse,
@ -716,7 +716,7 @@ async fn load_joined_room(
.state_cache .state_cache
.is_invited(&user_id, room_id)?) .is_invited(&user_id, room_id)?)
{ {
Ok::<_, Error>(Some(state_key.clone())) Ok::<_, Error>(Some(user_id))
} else { } else {
Ok(None) Ok(None)
} }
@ -1572,7 +1572,7 @@ pub async fn sync_events_v4_route(
sender_user.clone(), sender_user.clone(),
sender_device.clone(), sender_device.clone(),
conn_id.clone(), conn_id.clone(),
body.room_subscriptions, body.room_subscriptions.clone(),
); );
} }
@ -1638,33 +1638,37 @@ pub async fn sync_events_v4_route(
.get_member(room_id, &member) .get_member(room_id, &member)
.ok() .ok()
.flatten() .flatten()
.map(|memberevent| { .map(|memberevent| SlidingSyncRoomHero {
( user_id: member,
memberevent name: memberevent.displayname,
.displayname avatar: memberevent.avatar_url,
.unwrap_or_else(|| member.to_string()),
memberevent.avatar_url,
)
}) })
}) })
.take(5) .take(5)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let name = match &heroes[..] { let name = match &heroes[..] {
[] => None, [] => None,
[only] => Some(only.0.clone()), [only] => Some(
only.name
.clone()
.unwrap_or_else(|| only.user_id.to_string()),
),
[firsts @ .., last] => Some( [firsts @ .., last] => Some(
firsts firsts
.iter() .iter()
.map(|h| h.0.clone()) .map(|h| h.name.clone().unwrap_or_else(|| h.user_id.to_string()))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", ") .join(", ")
+ " and " + " and "
+ &last.0, + &last
.name
.clone()
.unwrap_or_else(|| last.user_id.to_string()),
), ),
}; };
let avatar = if let [only] = &heroes[..] { let avatar = if let [only] = &heroes[..] {
only.1.clone() only.avatar.clone()
} else { } else {
None None
}; };
@ -1725,6 +1729,16 @@ pub async fn sync_events_v4_route(
), ),
num_live: None, // Count events in timeline greater than global sync counter num_live: None, // Count events in timeline greater than global sync counter
timestamp: None, timestamp: None,
heroes: if body
.room_subscriptions
.get(room_id)
.map(|sub| sub.include_heroes.unwrap_or_default())
.unwrap_or_default()
{
Some(heroes)
} else {
None
},
}, },
); );
} }

View file

@ -17,7 +17,7 @@ pub async fn create_typing_event_route(
.is_joined(sender_user, &body.room_id)? .is_joined(sender_user, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"You are not in this room.", "You are not in this room.",
)); ));
} }

View file

@ -2,13 +2,14 @@ use std::{collections::BTreeMap, iter::FromIterator, str};
use axum::{ use axum::{
async_trait, async_trait,
body::{Full, HttpBody}, body::Body,
extract::{rejection::TypedHeaderRejectionReason, FromRequest, Path, TypedHeader}, extract::{FromRequest, Path},
headers::{authorization::Bearer, Authorization},
response::{IntoResponse, Response}, response::{IntoResponse, Response},
BoxError, RequestExt, RequestPartsExt, RequestExt, RequestPartsExt,
}; };
use bytes::{Buf, BufMut, Bytes, BytesMut}; use axum_extra::headers::authorization::Bearer;
use axum_extra::{headers::Authorization, typed_header::TypedHeaderRejectionReason, TypedHeader};
use bytes::{BufMut, BytesMut};
use http::{Request, StatusCode}; use http::{Request, StatusCode};
use ruma::{ use ruma::{
api::{client::error::ErrorKind, AuthScheme, IncomingRequest, OutgoingResponse}, api::{client::error::ErrorKind, AuthScheme, IncomingRequest, OutgoingResponse},
@ -29,37 +30,33 @@ enum Token {
} }
#[async_trait] #[async_trait]
impl<T, S, B> FromRequest<S, B> for Ruma<T> impl<T, S> FromRequest<S> for Ruma<T>
where where
T: IncomingRequest, T: IncomingRequest,
B: HttpBody + Send + 'static,
B::Data: Send,
B::Error: Into<BoxError>,
{ {
type Rejection = Error; type Rejection = Error;
async fn from_request(req: Request<B>, _state: &S) -> Result<Self, Self::Rejection> { async fn from_request(req: Request<Body>, _state: &S) -> Result<Self, Self::Rejection> {
#[derive(Deserialize)] #[derive(Deserialize)]
struct QueryParams { struct QueryParams {
access_token: Option<String>, access_token: Option<String>,
user_id: Option<String>, user_id: Option<String>,
} }
let (mut parts, mut body) = match req.with_limited_body() { let (mut parts, mut body) = {
Ok(limited_req) => { let limited_req = req.with_limited_body();
let (parts, body) = limited_req.into_parts(); let (parts, body) = limited_req.into_parts();
let body = to_bytes(body) let body = axum::body::to_bytes(
.await body,
.map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?; services()
(parts, body) .globals
} .max_request_size()
Err(original_req) => { .try_into()
let (parts, body) = original_req.into_parts(); .unwrap_or(usize::MAX),
let body = to_bytes(body) )
.await .await
.map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?; .map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?;
(parts, body) (parts, body)
}
}; };
let metadata = T::METADATA; let metadata = T::METADATA;
@ -135,7 +132,7 @@ where
if !services().users.exists(&user_id)? { if !services().users.exists(&user_id)? {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"User does not exist.", "User does not exist.",
)); ));
} }
@ -175,7 +172,7 @@ where
_ => "Unknown header-related error", _ => "Unknown header-related error",
}; };
Error::BadRequest(ErrorKind::Forbidden, msg) Error::BadRequest(ErrorKind::forbidden(), msg)
})?; })?;
if let Some(dest) = x_matrix.destination { if let Some(dest) = x_matrix.destination {
@ -242,7 +239,7 @@ where
Err(e) => { Err(e) => {
warn!("Failed to fetch signing keys: {}", e); warn!("Failed to fetch signing keys: {}", e);
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Failed to fetch signing keys.", "Failed to fetch signing keys.",
)); ));
} }
@ -268,7 +265,7 @@ where
} }
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Failed to verify X-Matrix signatures.", "Failed to verify X-Matrix signatures.",
)); ));
} }
@ -351,60 +348,8 @@ where
impl<T: OutgoingResponse> IntoResponse for RumaResponse<T> { impl<T: OutgoingResponse> IntoResponse for RumaResponse<T> {
fn into_response(self) -> Response { fn into_response(self) -> Response {
match self.0.try_into_http_response::<BytesMut>() { match self.0.try_into_http_response::<BytesMut>() {
Ok(res) => res.map(BytesMut::freeze).map(Full::new).into_response(), Ok(res) => res.map(BytesMut::freeze).map(Body::from).into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
} }
} }
} }
// copied from hyper under the following license:
// Copyright (c) 2014-2021 Sean McArthur
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
pub(crate) async fn to_bytes<T>(body: T) -> Result<Bytes, T::Error>
where
T: HttpBody,
{
futures_util::pin_mut!(body);
// If there's only 1 chunk, we can just return Buf::to_bytes()
let mut first = if let Some(buf) = body.data().await {
buf?
} else {
return Ok(Bytes::new());
};
let second = if let Some(buf) = body.data().await {
buf?
} else {
return Ok(first.copy_to_bytes(first.remaining()));
};
// With more than 1 buf, we gotta flatten into a Vec first.
let cap = first.remaining() + second.remaining() + body.size_hint().lower() as usize;
let mut vec = Vec::with_capacity(cap);
vec.put(first);
vec.put(second);
while let Some(buf) = body.data().await {
vec.put(buf?);
}
Ok(vec.into())
}

View file

@ -978,7 +978,7 @@ pub async fn get_event_route(
.server_in_room(sender_servername, room_id)? .server_in_room(sender_servername, room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Server is not in room", "Server is not in room",
)); ));
} }
@ -989,7 +989,7 @@ pub async fn get_event_route(
&body.event_id, &body.event_id,
)? { )? {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Server is not allowed to see event.", "Server is not allowed to see event.",
)); ));
} }
@ -1021,7 +1021,7 @@ pub async fn get_backfill_route(
.server_in_room(sender_servername, &body.room_id)? .server_in_room(sender_servername, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Server is not in room.", "Server is not in room.",
)); ));
} }
@ -1091,7 +1091,7 @@ pub async fn get_missing_events_route(
.server_in_room(sender_servername, &body.room_id)? .server_in_room(sender_servername, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Server is not in room", "Server is not in room",
)); ));
} }
@ -1176,7 +1176,7 @@ pub async fn get_event_authorization_route(
.server_in_room(sender_servername, &body.room_id)? .server_in_room(sender_servername, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Server is not in room.", "Server is not in room.",
)); ));
} }
@ -1234,7 +1234,7 @@ pub async fn get_room_state_route(
.server_in_room(sender_servername, &body.room_id)? .server_in_room(sender_servername, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Server is not in room.", "Server is not in room.",
)); ));
} }
@ -1310,7 +1310,7 @@ pub async fn get_room_state_ids_route(
.server_in_room(sender_servername, &body.room_id)? .server_in_room(sender_servername, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Server is not in room.", "Server is not in room.",
)); ));
} }

View file

@ -80,7 +80,7 @@ impl service::uiaa::Data for KeyValueDatabase {
.userdevicesessionid_uiaainfo .userdevicesessionid_uiaainfo
.get(&userdevicesessionid)? .get(&userdevicesessionid)?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"UIAA session does not exist.", "UIAA session does not exist.",
))?, ))?,
) )

View file

@ -1,6 +1,7 @@
use std::{future::Future, io, net::SocketAddr, sync::atomic, time::Duration}; use std::{future::Future, io, net::SocketAddr, sync::atomic, time::Duration};
use axum::{ use axum::{
body::Body,
extract::{DefaultBodyLimit, FromRequestParts, MatchedPath}, extract::{DefaultBodyLimit, FromRequestParts, MatchedPath},
middleware::map_response, middleware::map_response,
response::{IntoResponse, Response}, response::{IntoResponse, Response},
@ -69,11 +70,13 @@ async fn main() {
config.warn_deprecated(); config.warn_deprecated();
if config.allow_jaeger { if config.allow_jaeger {
opentelemetry::global::set_text_map_propagator(opentelemetry_jaeger::Propagator::new()); opentelemetry::global::set_text_map_propagator(
let tracer = opentelemetry_jaeger::new_agent_pipeline() opentelemetry_jaeger_propagator::Propagator::new(),
.with_auto_split_batch(true) );
.with_service_name("conduit") let tracer = opentelemetry_otlp::new_pipeline()
.install_batch(opentelemetry::runtime::Tokio) .tracing()
.with_exporter(opentelemetry_otlp::new_exporter().tonic())
.install_batch(opentelemetry_sdk::runtime::Tokio)
.unwrap(); .unwrap();
let telemetry = tracing_opentelemetry::layer().with_tracer(tracer); let telemetry = tracing_opentelemetry::layer().with_tracer(tracer);
@ -225,9 +228,9 @@ async fn run_server() -> io::Result<()> {
Ok(()) Ok(())
} }
async fn spawn_task<B: Send + 'static>( async fn spawn_task(
req: http::Request<B>, req: http::Request<Body>,
next: axum::middleware::Next<B>, next: axum::middleware::Next,
) -> std::result::Result<Response, StatusCode> { ) -> std::result::Result<Response, StatusCode> {
if services().globals.shutdown.load(atomic::Ordering::Relaxed) { if services().globals.shutdown.load(atomic::Ordering::Relaxed) {
return Err(StatusCode::SERVICE_UNAVAILABLE); return Err(StatusCode::SERVICE_UNAVAILABLE);
@ -237,9 +240,9 @@ async fn spawn_task<B: Send + 'static>(
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
} }
async fn unrecognized_method<B: Send>( async fn unrecognized_method(
req: http::Request<B>, req: http::Request<Body>,
next: axum::middleware::Next<B>, next: axum::middleware::Next,
) -> std::result::Result<Response, StatusCode> { ) -> std::result::Result<Response, StatusCode> {
let method = req.method().clone(); let method = req.method().clone();
let uri = req.uri().clone(); let uri = req.uri().clone();

View file

@ -10,11 +10,8 @@ use crate::api::server_server::FedDest;
use crate::{services, Config, Error, Result}; use crate::{services, Config, Error, Result};
use futures_util::FutureExt; use futures_util::FutureExt;
use hickory_resolver::TokioAsyncResolver; use hickory_resolver::TokioAsyncResolver;
use hyper::{ use hyper_util::client::legacy::connect::dns::{GaiResolver, Name as HyperName};
client::connect::dns::{GaiResolver, Name}, use reqwest::dns::{Addrs, Name, Resolve, Resolving};
service::Service as HyperService,
};
use reqwest::dns::{Addrs, Resolve, Resolving};
use ruma::{ use ruma::{
api::{ api::{
client::sync::sync_events, client::sync::sync_events,
@ -22,6 +19,7 @@ use ruma::{
}, },
DeviceId, RoomVersionId, ServerName, UserId, DeviceId, RoomVersionId, ServerName, UserId,
}; };
use std::str::FromStr;
use std::{ use std::{
collections::{BTreeMap, HashMap}, collections::{BTreeMap, HashMap},
error::Error as StdError, error::Error as StdError,
@ -37,6 +35,7 @@ use std::{
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use tokio::sync::{broadcast, watch::Receiver, Mutex, RwLock, Semaphore}; use tokio::sync::{broadcast, watch::Receiver, Mutex, RwLock, Semaphore};
use tower_service::Service as TowerService;
use tracing::{error, info}; use tracing::{error, info};
use base64::{engine::general_purpose, Engine as _}; use base64::{engine::general_purpose, Engine as _};
@ -139,11 +138,19 @@ impl Resolve for Resolver {
}) })
.unwrap_or_else(|| { .unwrap_or_else(|| {
let this = &mut self.inner.clone(); let this = &mut self.inner.clone();
Box::pin(HyperService::<Name>::call(this, name).map(|result| { Box::pin(
result TowerService::<HyperName>::call(
.map(|addrs| -> Addrs { Box::new(addrs) }) this,
.map_err(|err| -> Box<dyn StdError + Send + Sync> { Box::new(err) }) // Beautiful hack, please remove this in the future.
})) HyperName::from_str(name.as_str())
.expect("reqwest Name is just wrapper for hyper-util Name"),
)
.map(|result| {
result
.map(|addrs| -> Addrs { Box::new(addrs) })
.map_err(|err| -> Box<dyn StdError + Send + Sync> { Box::new(err) })
}),
)
}) })
} }
} }

View file

@ -133,7 +133,10 @@ impl Service {
match services().rooms.timeline.get_pdu(&event_id) { match services().rooms.timeline.get_pdu(&event_id) {
Ok(Some(pdu)) => { Ok(Some(pdu)) => {
if pdu.room_id != room_id { if pdu.room_id != room_id {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Evil event in db")); return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Evil event in db",
));
} }
for auth_event in &pdu.auth_events { for auth_event in &pdu.auth_events {
let sauthevent = services() let sauthevent = services()

View file

@ -90,7 +90,7 @@ impl Service {
if services().rooms.metadata.is_disabled(room_id)? { if services().rooms.metadata.is_disabled(room_id)? {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Federation of this room is currently disabled on this server.", "Federation of this room is currently disabled on this server.",
)); ));
} }
@ -162,7 +162,7 @@ impl Service {
// Check for disabled again because it might have changed // Check for disabled again because it might have changed
if services().rooms.metadata.is_disabled(room_id)? { if services().rooms.metadata.is_disabled(room_id)? {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Federation of this room is currently disabled on this server.", "Federation of this room is currently disabled on this server.",
)); ));
} }
@ -1668,7 +1668,7 @@ impl Service {
server_name, room_id server_name, room_id
); );
Err(Error::BadRequest( Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Server was denied by room ACL", "Server was denied by room ACL",
)) ))
} }

View file

@ -408,7 +408,7 @@ impl Service {
debug!("User is not allowed to see room {room_id}"); debug!("User is not allowed to see room {room_id}");
// This error will be caught later // This error will be caught later
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"User is not allowed to see the room", "User is not allowed to see the room",
)); ));
} }

View file

@ -762,7 +762,7 @@ impl Service {
if !auth_check { if !auth_check {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Event is not authorized.", "Event is not authorized.",
)); ));
} }
@ -842,7 +842,7 @@ impl Service {
TimelineEventType::RoomEncryption => { TimelineEventType::RoomEncryption => {
warn!("Encryption is not allowed in the admins room"); warn!("Encryption is not allowed in the admins room");
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Encryption is not allowed in the admins room.", "Encryption is not allowed in the admins room.",
)); ));
} }
@ -865,7 +865,7 @@ impl Service {
if target == server_user { if target == server_user {
warn!("Conduit user cannot leave from admins room"); warn!("Conduit user cannot leave from admins room");
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Conduit user cannot leave from admins room.", "Conduit user cannot leave from admins room.",
)); ));
} }
@ -881,7 +881,7 @@ impl Service {
if count < 2 { if count < 2 {
warn!("Last admin cannot leave from admins room"); warn!("Last admin cannot leave from admins room");
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Last admin cannot leave from admins room.", "Last admin cannot leave from admins room.",
)); ));
} }
@ -891,7 +891,7 @@ impl Service {
if target == server_user { if target == server_user {
warn!("Conduit user cannot be banned in admins room"); warn!("Conduit user cannot be banned in admins room");
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Conduit user cannot be banned in admins room.", "Conduit user cannot be banned in admins room.",
)); ));
} }
@ -907,7 +907,7 @@ impl Service {
if count < 2 { if count < 2 {
warn!("Last admin cannot be banned in admins room"); warn!("Last admin cannot be banned in admins room");
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"Last admin cannot be banned in admins room.", "Last admin cannot be banned in admins room.",
)); ));
} }
@ -939,7 +939,7 @@ impl Service {
false, false,
)? { )? {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"User cannot redact this event.", "User cannot redact this event.",
)); ));
} }
@ -960,7 +960,7 @@ impl Service {
false, false,
)? { )? {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::forbidden(),
"User cannot redact this event.", "User cannot redact this event.",
)); ));
} }

View file

@ -86,7 +86,7 @@ impl Service {
if !hash_matches { if !hash_matches {
uiaainfo.auth_error = Some(ruma::api::client::error::StandardErrorBody { uiaainfo.auth_error = Some(ruma::api::client::error::StandardErrorBody {
kind: ErrorKind::Forbidden, kind: ErrorKind::forbidden(),
message: "Invalid username or password.".to_owned(), message: "Invalid username or password.".to_owned(),
}); });
return Ok((false, uiaainfo)); return Ok((false, uiaainfo));
@ -101,7 +101,7 @@ impl Service {
uiaainfo.completed.push(AuthType::RegistrationToken); uiaainfo.completed.push(AuthType::RegistrationToken);
} else { } else {
uiaainfo.auth_error = Some(ruma::api::client::error::StandardErrorBody { uiaainfo.auth_error = Some(ruma::api::client::error::StandardErrorBody {
kind: ErrorKind::Forbidden, kind: ErrorKind::forbidden(),
message: "Invalid registration token.".to_owned(), message: "Invalid registration token.".to_owned(),
}); });
return Ok((false, uiaainfo)); return Ok((false, uiaainfo));

View file

@ -128,7 +128,7 @@ impl Error {
kind.clone(), kind.clone(),
match kind { match kind {
WrongRoomKeysVersion { .. } WrongRoomKeysVersion { .. }
| Forbidden | Forbidden { .. }
| GuestAccessForbidden | GuestAccessForbidden
| ThreepidAuthFailed | ThreepidAuthFailed
| ThreepidDenied => StatusCode::FORBIDDEN, | ThreepidDenied => StatusCode::FORBIDDEN,