Bump ruma

This commit is contained in:
Timo Kösters 2022-10-09 17:25:06 +02:00 committed by Nyaaori
parent 275c6b447d
commit 6b131202b9
No known key found for this signature in database
GPG key ID: E7819C3ED4D1F82E
68 changed files with 446 additions and 347 deletions

View file

@ -193,6 +193,8 @@ pub async fn register_route(
access_token: None,
user_id,
device_id: None,
refresh_token: None,
expires_in: None,
});
}
@ -238,6 +240,8 @@ pub async fn register_route(
access_token: Some(token),
user_id,
device_id: Some(device_id),
refresh_token: None,
expires_in: None,
})
}

View file

@ -19,6 +19,7 @@ use ruma::{
room::{
avatar::RoomAvatarEventContent,
canonical_alias::RoomCanonicalAliasEventContent,
create::RoomCreateEventContent,
guest_access::{GuestAccess, RoomGuestAccessEventContent},
history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
join_rules::{JoinRule, RoomJoinRulesEventContent},
@ -135,6 +136,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
since,
filter: Filter {
generic_search_term: filter.generic_search_term.as_deref(),
room_types: filter.room_types.clone(),
},
room_network: RoomNetwork::Matrix,
},
@ -287,6 +289,20 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.transpose()?
.flatten()
.ok_or_else(|| Error::bad_database("Missing room join rule event for room."))?,
room_type: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomCreate, "")?
.map(|s| {
serde_json::from_str::<RoomCreateEventContent>(s.content.get()).map_err(
|e| {
error!("Invalid room create event in database: {}", e);
Error::BadDatabase("Invalid room create event in database.")
},
)
})
.transpose()?
.and_then(|e| e.room_type),
room_id,
};
Ok(chunk)

View file

@ -14,7 +14,7 @@ use ruma::{
federation,
},
serde::Raw,
DeviceId, DeviceKeyAlgorithm, UserId,
DeviceId, DeviceKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId,
};
use serde_json::json;
use std::collections::{BTreeMap, HashMap, HashSet};
@ -253,7 +253,7 @@ pub async fn get_key_changes_route(
pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
sender_user: Option<&UserId>,
device_keys_input: &BTreeMap<Box<UserId>, Vec<Box<DeviceId>>>,
device_keys_input: &BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>,
allowed_signatures: F,
) -> Result<get_keys::v3::Response> {
let mut master_keys = BTreeMap::new();
@ -396,7 +396,7 @@ fn add_unsigned_device_display_name(
}
pub(crate) async fn claim_keys_helper(
one_time_keys_input: &BTreeMap<Box<UserId>, BTreeMap<Box<DeviceId>, DeviceKeyAlgorithm>>,
one_time_keys_input: &BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, DeviceKeyAlgorithm>>,
) -> Result<claim_keys::v3::Response> {
let mut one_time_keys = BTreeMap::new();

View file

@ -10,12 +10,14 @@ use ruma::{
},
federation::{self, membership::create_invite},
},
canonical_json::to_canonical_value,
events::{
room::member::{MembershipState, RoomMemberEventContent},
RoomEventType, StateEventType,
},
serde::{to_canonical_value, Base64, CanonicalJsonObject, CanonicalJsonValue},
EventId, RoomId, RoomVersionId, ServerName, UserId,
serde::Base64,
CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, OwnedRoomId, OwnedServerName,
RoomId, RoomVersionId, UserId,
};
use serde_json::value::{to_raw_value, RawValue as RawJsonValue};
use std::{
@ -83,7 +85,7 @@ pub async fn join_room_by_id_or_alias_route(
let sender_user = body.sender_user.as_deref().expect("user is authenticated");
let body = body.body;
let (servers, room_id) = match Box::<RoomId>::try_from(body.room_id_or_alias) {
let (servers, room_id) = match OwnedRoomId::try_from(body.room_id_or_alias) {
Ok(room_id) => {
let mut servers = body.server_name.clone();
servers.extend(
@ -458,7 +460,7 @@ pub async fn joined_members_route(
async fn join_room_by_id_helper(
sender_user: Option<&UserId>,
room_id: &RoomId,
servers: &[Box<ServerName>],
servers: &[OwnedServerName],
_third_party_signed: Option<&IncomingThirdPartySigned>,
) -> Result<join_room_by_id::v3::Response> {
let sender_user = sender_user.expect("user is authenticated");
@ -673,7 +675,12 @@ async fn join_room_by_id_helper(
room_id,
state
.into_iter()
.map(|(k, id)| services().rooms.state_compressor.compress_state_event(k, &id))
.map(|(k, id)| {
services()
.rooms
.state_compressor
.compress_state_event(k, &id)
})
.collect::<Result<_>>()?,
)?;
@ -737,7 +744,7 @@ fn validate_and_add_event_id(
pdu: &RawJsonValue,
room_version: &RoomVersionId,
pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, Base64>>>,
) -> Result<(Box<EventId>, CanonicalJsonObject)> {
) -> Result<(OwnedEventId, CanonicalJsonObject)> {
let mut value: CanonicalJsonObject = serde_json::from_str(pdu.get()).map_err(|e| {
error!("Invalid PDU in server response: {:?}: {:?}", pdu, e);
Error::BadServerResponse("Invalid PDU in server response")
@ -896,7 +903,7 @@ pub(crate) async fn invite_helper<'a>(
warn!("Server {} changed invite event, that's not allowed in the spec: ours: {:?}, theirs: {:?}", user_id.server_name(), pdu_json, value);
}
let origin: Box<ServerName> = serde_json::from_value(
let origin: OwnedServerName = serde_json::from_value(
serde_json::to_value(value.get("origin").ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Event needs an origin field.",

View file

@ -1,8 +1,7 @@
use crate::{services, Error, Result, Ruma};
use ruma::{
api::client::{error::ErrorKind, read_marker::set_read_marker, receipt::create_receipt},
events::RoomAccountDataEventType,
receipt::ReceiptType,
events::{receipt::ReceiptType, RoomAccountDataEventType},
MilliSecondsSinceUnixEpoch,
};
use std::collections::BTreeMap;
@ -18,19 +17,28 @@ pub async fn set_read_marker_route(
) -> Result<set_read_marker::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let fully_read_event = ruma::events::fully_read::FullyReadEvent {
content: ruma::events::fully_read::FullyReadEventContent {
event_id: body.fully_read.clone(),
},
};
services().account_data.update(
Some(&body.room_id),
sender_user,
RoomAccountDataEventType::FullyRead,
&serde_json::to_value(fully_read_event).expect("to json value always works"),
)?;
if let Some(fully_read) = &body.fully_read {
let fully_read_event = ruma::events::fully_read::FullyReadEvent {
content: ruma::events::fully_read::FullyReadEventContent {
event_id: fully_read.clone(),
},
};
services().account_data.update(
Some(&body.room_id),
sender_user,
RoomAccountDataEventType::FullyRead,
&serde_json::to_value(fully_read_event).expect("to json value always works"),
)?;
}
if let Some(event) = &body.read_receipt {
if body.private_read_receipt.is_some() || body.read_receipt.is_some() {
services()
.rooms
.user
.reset_notification_counts(sender_user, &body.room_id)?;
}
if let Some(event) = &body.private_read_receipt {
services().rooms.edus.read_receipt.private_read_set(
&body.room_id,
sender_user,
@ -43,11 +51,9 @@ pub async fn set_read_marker_route(
"Event does not exist.",
))?,
)?;
services()
.rooms
.user
.reset_notification_counts(sender_user, &body.room_id)?;
}
if let Some(event) = &body.read_receipt {
let mut user_receipts = BTreeMap::new();
user_receipts.insert(
sender_user.clone(),
@ -83,44 +89,69 @@ pub async fn create_receipt_route(
) -> Result<create_receipt::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().rooms.edus.read_receipt.private_read_set(
&body.room_id,
sender_user,
if matches!(
&body.receipt_type,
create_receipt::v3::ReceiptType::Read | create_receipt::v3::ReceiptType::ReadPrivate
) {
services()
.rooms
.timeline
.get_pdu_count(&body.event_id)?
.ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Event does not exist.",
))?,
)?;
services()
.rooms
.user
.reset_notification_counts(sender_user, &body.room_id)?;
.user
.reset_notification_counts(sender_user, &body.room_id)?;
}
let mut user_receipts = BTreeMap::new();
user_receipts.insert(
sender_user.clone(),
ruma::events::receipt::Receipt {
ts: Some(MilliSecondsSinceUnixEpoch::now()),
},
);
let mut receipts = BTreeMap::new();
receipts.insert(ReceiptType::Read, user_receipts);
match body.receipt_type {
create_receipt::v3::ReceiptType::FullyRead => {
let fully_read_event = ruma::events::fully_read::FullyReadEvent {
content: ruma::events::fully_read::FullyReadEventContent {
event_id: body.event_id.clone(),
},
};
services().account_data.update(
Some(&body.room_id),
sender_user,
RoomAccountDataEventType::FullyRead,
&serde_json::to_value(fully_read_event).expect("to json value always works"),
)?;
}
create_receipt::v3::ReceiptType::Read => {
let mut user_receipts = BTreeMap::new();
user_receipts.insert(
sender_user.clone(),
ruma::events::receipt::Receipt {
ts: Some(MilliSecondsSinceUnixEpoch::now()),
},
);
let mut receipts = BTreeMap::new();
receipts.insert(ReceiptType::Read, user_receipts);
let mut receipt_content = BTreeMap::new();
receipt_content.insert(body.event_id.to_owned(), receipts);
let mut receipt_content = BTreeMap::new();
receipt_content.insert(body.event_id.to_owned(), receipts);
services().rooms.edus.read_receipt.readreceipt_update(
sender_user,
&body.room_id,
ruma::events::receipt::ReceiptEvent {
content: ruma::events::receipt::ReceiptEventContent(receipt_content),
room_id: body.room_id.clone(),
},
)?;
services().rooms.edus.read_receipt.readreceipt_update(
sender_user,
&body.room_id,
ruma::events::receipt::ReceiptEvent {
content: ruma::events::receipt::ReceiptEventContent(receipt_content),
room_id: body.room_id.clone(),
},
)?;
}
create_receipt::v3::ReceiptType::ReadPrivate => {
services().rooms.edus.read_receipt.private_read_set(
&body.room_id,
sender_user,
services()
.rooms
.timeline
.get_pdu_count(&body.event_id)?
.ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Event does not exist.",
))?,
)?;
}
_ => return Err(Error::bad_database("Unsupported receipt type")),
}
Ok(create_receipt::v3::Response {})
}

View file

@ -1,6 +1,8 @@
use crate::{
api::client_server::invite_helper, service::pdu::PduBuilder, services, Error, Result, Ruma,
};
use ruma::serde::JsonObject;
use ruma::OwnedRoomAliasId;
use ruma::{
api::client::{
error::ErrorKind,
@ -21,9 +23,7 @@ use ruma::{
},
RoomEventType, StateEventType,
},
int,
serde::{CanonicalJsonObject, JsonObject},
RoomAliasId, RoomId,
int, CanonicalJsonObject, RoomAliasId, RoomId,
};
use serde_json::{json, value::to_raw_value};
use std::{cmp::max, collections::BTreeMap, sync::Arc};
@ -77,7 +77,7 @@ pub async fn create_room_route(
));
}
let alias: Option<Box<RoomAliasId>> =
let alias: Option<OwnedRoomAliasId> =
body.room_alias_name
.as_ref()
.map_or(Ok(None), |localpart| {

View file

@ -147,6 +147,8 @@ pub async fn login_route(body: Ruma<login::v3::IncomingRequest>) -> Result<login
home_server: Some(services().globals.server_name().to_owned()),
device_id,
well_known: None,
refresh_token: None,
expires_in: None,
})
}

View file

@ -2,7 +2,7 @@ use crate::{services, Error, Result, Ruma, RumaResponse};
use ruma::{
api::client::{
filter::{IncomingFilterDefinition, LazyLoadOptions},
sync::sync_events,
sync::sync_events::{self, DeviceLists, UnreadNotificationsCount},
uiaa::UiaaResponse,
},
events::{
@ -10,7 +10,7 @@ use ruma::{
RoomEventType, StateEventType,
},
serde::Raw,
DeviceId, RoomId, UserId,
DeviceId, OwnedDeviceId, OwnedUserId, RoomId, UserId,
};
use std::{
collections::{hash_map::Entry, BTreeMap, HashMap, HashSet},
@ -122,8 +122,8 @@ pub async fn sync_events_route(
}
async fn sync_helper_wrapper(
sender_user: Box<UserId>,
sender_device: Box<DeviceId>,
sender_user: OwnedUserId,
sender_device: OwnedDeviceId,
body: sync_events::v3::IncomingRequest,
tx: Sender<Option<Result<sync_events::v3::Response>>>,
) {
@ -155,15 +155,14 @@ async fn sync_helper_wrapper(
}
async fn sync_helper(
sender_user: Box<UserId>,
sender_device: Box<DeviceId>,
sender_user: OwnedUserId,
sender_device: OwnedDeviceId,
body: sync_events::v3::IncomingRequest,
// bool = caching allowed
) -> Result<(sync_events::v3::Response, bool), Error> {
use sync_events::v3::{
DeviceLists, Ephemeral, GlobalAccountData, IncomingFilter, InviteState, InvitedRoom,
JoinedRoom, LeftRoom, Presence, RoomAccountData, RoomSummary, Rooms, State, Timeline,
ToDevice, UnreadNotificationsCount,
Ephemeral, GlobalAccountData, IncomingFilter, InviteState, InvitedRoom, JoinedRoom,
LeftRoom, Presence, RoomAccountData, RoomSummary, Rooms, State, Timeline, ToDevice,
};
// TODO: match body.set_presence {
@ -444,7 +443,7 @@ async fn sync_helper(
};
// This check is in case a bad user ID made it into the database
if let Ok(uid) = UserId::parse(state_key.as_ref()) {
if let Ok(uid) = UserId::parse(&state_key) {
lazy_loaded.insert(uid);
}
state_events.push(pdu);

View file

@ -17,8 +17,7 @@ use bytes::{BufMut, Bytes, BytesMut};
use http::StatusCode;
use ruma::{
api::{client::error::ErrorKind, AuthScheme, IncomingRequest, OutgoingResponse},
signatures::CanonicalJsonValue,
DeviceId, ServerName, UserId,
CanonicalJsonValue, DeviceId, OwnedDeviceId, OwnedServerName, ServerName, UserId,
};
use serde::Deserialize;
use tracing::{debug, error, warn};
@ -81,7 +80,7 @@ where
let (sender_user, sender_device, sender_servername, from_appservice) =
if let Some((_id, registration)) = appservice_registration {
match metadata.authentication {
AuthScheme::AccessToken | AuthScheme::QueryOnlyAccessToken => {
AuthScheme::AccessToken => {
let user_id = query_params.user_id.map_or_else(
|| {
UserId::parse_with_server_name(
@ -112,7 +111,7 @@ where
}
} else {
match metadata.authentication {
AuthScheme::AccessToken | AuthScheme::QueryOnlyAccessToken => {
AuthScheme::AccessToken => {
let token = match token {
Some(token) => token,
_ => {
@ -132,7 +131,7 @@ where
}
Some((user_id, device_id)) => (
Some(user_id),
Some(Box::<DeviceId>::from(device_id)),
Some(OwnedDeviceId::from(device_id)),
None,
false,
),
@ -298,7 +297,7 @@ where
}
struct XMatrix {
origin: Box<ServerName>,
origin: OwnedServerName,
key: String, // KeyName?
sig: String,
}

View file

@ -1,6 +1,7 @@
use crate::Error;
use ruma::{
api::client::uiaa::UiaaResponse, signatures::CanonicalJsonValue, DeviceId, ServerName, UserId,
api::client::uiaa::UiaaResponse, CanonicalJsonValue, OwnedDeviceId, OwnedServerName,
OwnedUserId,
};
use std::ops::Deref;
@ -10,9 +11,9 @@ mod axum;
/// Extractor for Ruma request structs
pub struct Ruma<T> {
pub body: T,
pub sender_user: Option<Box<UserId>>,
pub sender_device: Option<Box<DeviceId>>,
pub sender_servername: Option<Box<ServerName>>,
pub sender_user: Option<OwnedUserId>,
pub sender_device: Option<OwnedDeviceId>,
pub sender_servername: Option<OwnedServerName>,
// This is None when body is not a valid string
pub json_body: Option<CanonicalJsonValue>,
pub from_appservice: bool,

View file

@ -33,18 +33,17 @@ use ruma::{
},
directory::{IncomingFilter, IncomingRoomNetwork},
events::{
receipt::{ReceiptEvent, ReceiptEventContent},
receipt::{ReceiptEvent, ReceiptEventContent, ReceiptType},
room::{
join_rules::{JoinRule, RoomJoinRulesEventContent},
member::{MembershipState, RoomMemberEventContent},
},
RoomEventType, StateEventType,
},
receipt::ReceiptType,
serde::{Base64, JsonObject, Raw},
signatures::CanonicalJsonValue,
to_device::DeviceIdOrAllDevices,
EventId, MilliSecondsSinceUnixEpoch, RoomId, ServerName, ServerSigningKeyId,
CanonicalJsonValue, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId,
OwnedServerName, OwnedServerSigningKeyId, OwnedUserId, RoomId, ServerName, ServerSigningKeyId,
};
use serde_json::value::{to_raw_value, RawValue as RawJsonValue};
use std::{
@ -280,7 +279,7 @@ where
.write()
.unwrap()
.insert(
Box::<ServerName>::from(destination),
OwnedServerName::from(destination),
(actual_destination, host),
);
}
@ -528,7 +527,7 @@ pub async fn get_server_keys_route() -> Result<impl IntoResponse> {
return Err(Error::bad_config("Federation is disabled."));
}
let mut verify_keys: BTreeMap<Box<ServerSigningKeyId>, VerifyKey> = BTreeMap::new();
let mut verify_keys: BTreeMap<OwnedServerSigningKeyId, VerifyKey> = BTreeMap::new();
verify_keys.insert(
format!("ed25519:{}", services().globals.keypair().version())
.try_into()
@ -669,7 +668,7 @@ pub async fn send_transaction_message_route(
};
// 0. Check the server is in the room
let room_id = match value
let room_id: OwnedRoomId = match value
.get("room_id")
.and_then(|id| RoomId::parse(id.as_str()?).ok())
{
@ -1007,7 +1006,7 @@ pub async fn get_missing_events_route(
continue;
}
queued_events.extend_from_slice(
&serde_json::from_value::<Vec<Box<EventId>>>(
&serde_json::from_value::<Vec<OwnedEventId>>(
serde_json::to_value(pdu.get("prev_events").cloned().ok_or_else(|| {
Error::bad_database("Event in db has no prev_events field.")
})?)
@ -1411,7 +1410,7 @@ async fn create_join_event(
}
};
let origin: Box<ServerName> = serde_json::from_value(
let origin: OwnedServerName = serde_json::from_value(
serde_json::to_value(value.get("origin").ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Event needs an origin field.",
@ -1474,6 +1473,7 @@ async fn create_join_event(
.filter_map(|(_, id)| services().rooms.timeline.get_pdu_json(id).ok().flatten())
.map(PduEvent::convert_to_outgoing_federation_event)
.collect(),
origin: services().globals.server_name().to_string(),
})
}
@ -1564,10 +1564,10 @@ pub async fn create_invite_route(
// Add event_id back
signed_event.insert(
"event_id".to_owned(),
CanonicalJsonValue::String(event_id.into()),
CanonicalJsonValue::String(event_id.to_string()),
);
let sender: Box<_> = serde_json::from_value(
let sender: OwnedUserId = serde_json::from_value(
signed_event
.get("sender")
.ok_or(Error::BadRequest(