From 814e68fb4db003e0f6c80942c3bbde43c8bcf30b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timo=20K=C3=B6sters?= Date: Sun, 18 Oct 2020 11:18:43 +0200 Subject: [PATCH] WIP move to ruma master. Waiting for value->canonicaljsonobject helper --- Cargo.lock | 50 +++++++++++++++-------- Cargo.toml | 6 +-- src/client_server/backup.rs | 27 +++++++------ src/client_server/capabilities.rs | 13 +++--- src/client_server/filter.rs | 11 +---- src/client_server/keys.rs | 8 ++-- src/client_server/media.rs | 10 ++--- src/client_server/membership.rs | 28 +++++++++---- src/client_server/state.rs | 6 +-- src/database/media.rs | 67 +++++++++++++++++++------------ src/database/rooms.rs | 5 ++- src/database/users.rs | 6 +-- src/pdu.rs | 4 +- src/ruma_wrapper.rs | 47 ++++++++++++---------- src/server_server.rs | 7 ++-- 15 files changed, 173 insertions(+), 122 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6fed2af..3624480 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1559,8 +1559,10 @@ dependencies = [ [[package]] name = "ruma" version = "0.0.1" -source = "git+https://github.com/timokoesters/ruma?branch=timo-fed-fixes#47fab87325b71b7f6c2fb3cd276d1f813e42abf7" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" dependencies = [ + "assign", + "js_int", "ruma-api", "ruma-appservice-api", "ruma-client-api", @@ -1575,22 +1577,24 @@ dependencies = [ [[package]] name = "ruma-api" version = "0.17.0-alpha.1" -source = "git+https://github.com/timokoesters/ruma?branch=timo-fed-fixes#47fab87325b71b7f6c2fb3cd276d1f813e42abf7" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" dependencies = [ "http", "percent-encoding", "ruma-api-macros", + "ruma-common", "ruma-identifiers", "ruma-serde", "serde", "serde_json", "strum", + "thiserror", ] [[package]] name = "ruma-api-macros" version = "0.17.0-alpha.1" -source = "git+https://github.com/timokoesters/ruma?branch=timo-fed-fixes#47fab87325b71b7f6c2fb3cd276d1f813e42abf7" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -1601,7 +1605,7 @@ dependencies = [ [[package]] name = "ruma-appservice-api" version = "0.2.0-alpha.1" -source = "git+https://github.com/timokoesters/ruma?branch=timo-fed-fixes#47fab87325b71b7f6c2fb3cd276d1f813e42abf7" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" dependencies = [ "ruma-api", "ruma-common", @@ -1614,11 +1618,12 @@ dependencies = [ [[package]] name = "ruma-client-api" version = "0.10.0-alpha.1" -source = "git+https://github.com/timokoesters/ruma?branch=timo-fed-fixes#47fab87325b71b7f6c2fb3cd276d1f813e42abf7" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" dependencies = [ "assign", "http", "js_int", + "maplit", "percent-encoding", "ruma-api", "ruma-common", @@ -1633,10 +1638,10 @@ dependencies = [ [[package]] name = "ruma-common" version = "0.2.0" -source = "git+https://github.com/timokoesters/ruma?branch=timo-fed-fixes#47fab87325b71b7f6c2fb3cd276d1f813e42abf7" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" dependencies = [ "js_int", - "ruma-api", + "ruma-common-macros", "ruma-identifiers", "ruma-serde", "serde", @@ -1644,10 +1649,21 @@ dependencies = [ "strum", ] +[[package]] +name = "ruma-common-macros" +version = "0.2.0" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "ruma-events" version = "0.22.0-alpha.1" -source = "git+https://github.com/timokoesters/ruma?branch=timo-fed-fixes#47fab87325b71b7f6c2fb3cd276d1f813e42abf7" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" dependencies = [ "js_int", "ruma-common", @@ -1662,7 +1678,7 @@ dependencies = [ [[package]] name = "ruma-events-macros" version = "0.22.0-alpha.1" -source = "git+https://github.com/timokoesters/ruma?branch=timo-fed-fixes#47fab87325b71b7f6c2fb3cd276d1f813e42abf7" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -1673,7 +1689,7 @@ dependencies = [ [[package]] name = "ruma-federation-api" version = "0.0.3" -source = "git+https://github.com/timokoesters/ruma?branch=timo-fed-fixes#47fab87325b71b7f6c2fb3cd276d1f813e42abf7" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" dependencies = [ "js_int", "ruma-api", @@ -1688,7 +1704,7 @@ dependencies = [ [[package]] name = "ruma-identifiers" version = "0.17.4" -source = "git+https://github.com/timokoesters/ruma?branch=timo-fed-fixes#47fab87325b71b7f6c2fb3cd276d1f813e42abf7" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" dependencies = [ "rand", "ruma-identifiers-macros", @@ -1700,7 +1716,7 @@ dependencies = [ [[package]] name = "ruma-identifiers-macros" version = "0.17.4" -source = "git+https://github.com/timokoesters/ruma?branch=timo-fed-fixes#47fab87325b71b7f6c2fb3cd276d1f813e42abf7" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" dependencies = [ "proc-macro2", "quote", @@ -1711,7 +1727,7 @@ dependencies = [ [[package]] name = "ruma-identifiers-validation" version = "0.1.1" -source = "git+https://github.com/timokoesters/ruma?branch=timo-fed-fixes#47fab87325b71b7f6c2fb3cd276d1f813e42abf7" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" dependencies = [ "serde", "strum", @@ -1720,7 +1736,7 @@ dependencies = [ [[package]] name = "ruma-serde" version = "0.2.3" -source = "git+https://github.com/timokoesters/ruma?branch=timo-fed-fixes#47fab87325b71b7f6c2fb3cd276d1f813e42abf7" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" dependencies = [ "form_urlencoded", "itoa", @@ -1732,10 +1748,12 @@ dependencies = [ [[package]] name = "ruma-signatures" version = "0.6.0-dev.1" -source = "git+https://github.com/timokoesters/ruma?branch=timo-fed-fixes#47fab87325b71b7f6c2fb3cd276d1f813e42abf7" +source = "git+https://github.com/ruma/ruma?rev=f85d98f557b457fdf9846b851055a5fbab2eeee2#f85d98f557b457fdf9846b851055a5fbab2eeee2" dependencies = [ "base64", "ring", + "ruma-identifiers", + "ruma-serde", "serde_json", "untrusted", ] @@ -1982,7 +2000,7 @@ checksum = "7345c971d1ef21ffdbd103a75990a15eb03604fc8b8852ca8cb418ee1a099028" [[package]] name = "state-res" version = "0.1.0" -source = "git+https://github.com/timokoesters/state-res?branch=spec-comp#a7d76935f12757aecfee305838069c9bcbe7d34a" +source = "git+https://github.com/timokoesters/state-res?branch=spec-comp-ruma-master#79f2c8004106b60f57b404e4f84b6225fc663e27" dependencies = [ "itertools", "js_int", diff --git a/Cargo.toml b/Cargo.toml index 8b29be8..7ad12a9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,12 +18,12 @@ edition = "2018" rocket = { git = "https://github.com/timokoesters/Rocket.git", branch = "empty_parameters", default-features = false, features = ["tls"] } # Used for matrix spec type definitions and helpers -#ruma = { git = "https://github.com/ruma/ruma", features = ["rand", "client-api", "federation-api", "unstable-pre-spec", "unstable-synapse-quirks"], rev = "aff914050eb297bd82b8aafb12158c88a9e480e1" } -ruma = { git = "https://github.com/timokoesters/ruma", features = ["rand", "client-api", "federation-api", "unstable-exhaustive-types", "unstable-pre-spec", "unstable-synapse-quirks"], branch = "timo-fed-fixes" } +ruma = { git = "https://github.com/ruma/ruma", features = ["rand", "client-api", "federation-api", "unstable-pre-spec", "unstable-synapse-quirks", "unstable-exhaustive-types"], rev = "f85d98f557b457fdf9846b851055a5fbab2eeee2" } +#ruma = { git = "https://github.com/timokoesters/ruma", features = ["rand", "client-api", "federation-api", "unstable-exhaustive-types", "unstable-pre-spec", "unstable-synapse-quirks"], branch = "timo-fed-fixes" } #ruma = { path = "../ruma/ruma", features = ["unstable-exhaustive-types", "rand", "client-api", "federation-api", "unstable-pre-spec", "unstable-synapse-quirks"] } # Used when doing state resolution -state-res = { git = "https://github.com/timokoesters/state-res", branch = "spec-comp", features = ["unstable-pre-spec"] } +state-res = { git = "https://github.com/timokoesters/state-res", branch = "spec-comp-ruma-master", features = ["unstable-pre-spec"] } #state-res = { path = "../state-res", features = ["unstable-pre-spec"] } # Used for long polling diff --git a/src/client_server/backup.rs b/src/client_server/backup.rs index c84af0a..965ba1b 100644 --- a/src/client_server/backup.rs +++ b/src/client_server/backup.rs @@ -107,7 +107,7 @@ pub async fn get_backup_route( )] pub async fn delete_backup_route( db: State<'_, Database>, - body: Ruma, + body: Ruma>, ) -> ConduitResult { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -158,7 +158,7 @@ pub async fn add_backup_keys_route( )] pub async fn add_backup_key_sessions_route( db: State<'_, Database>, - body: Ruma, + body: Ruma>, ) -> ConduitResult { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -189,7 +189,7 @@ pub async fn add_backup_key_sessions_route( )] pub async fn add_backup_key_session_route( db: State<'_, Database>, - body: Ruma, + body: Ruma>, ) -> ConduitResult { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -232,7 +232,7 @@ pub async fn get_backup_keys_route( )] pub async fn get_backup_key_sessions_route( db: State<'_, Database>, - body: Ruma, + body: Ruma>, ) -> ConduitResult { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -249,15 +249,18 @@ pub async fn get_backup_key_sessions_route( )] pub async fn get_backup_key_session_route( db: State<'_, Database>, - body: Ruma, + body: Ruma>, ) -> ConduitResult { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); - let key_data = + if let Some(key_data) = db.key_backups - .get_session(&sender_user, &body.version, &body.room_id, &body.session_id)?; - - Ok(get_backup_key_session::Response { key_data }.into()) + .get_session(&sender_user, &body.version, &body.room_id, &body.session_id)? + { + Ok(get_backup_key_session::Response { key_data }.into()) + } else { + Err(Error::BadRequest(ErrorKind::NotFound, "Key not found.").into()) + } } #[cfg_attr( @@ -266,7 +269,7 @@ pub async fn get_backup_key_session_route( )] pub async fn delete_backup_keys_route( db: State<'_, Database>, - body: Ruma, + body: Ruma>, ) -> ConduitResult { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -288,7 +291,7 @@ pub async fn delete_backup_keys_route( )] pub async fn delete_backup_key_sessions_route( db: State<'_, Database>, - body: Ruma, + body: Ruma>, ) -> ConduitResult { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -310,7 +313,7 @@ pub async fn delete_backup_key_sessions_route( )] pub async fn delete_backup_key_session_route( db: State<'_, Database>, - body: Ruma, + body: Ruma>, ) -> ConduitResult { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); diff --git a/src/client_server/capabilities.rs b/src/client_server/capabilities.rs index 54c08ba..4ce67d3 100644 --- a/src/client_server/capabilities.rs +++ b/src/client_server/capabilities.rs @@ -1,5 +1,8 @@ use crate::ConduitResult; -use ruma::{api::client::r0::capabilities::get_capabilities, RoomVersionId}; +use ruma::{ + api::client::r0::capabilities::get_capabilities::{self, ChangePasswordCapability}, + RoomVersionId, +}; use std::collections::BTreeMap; #[cfg(feature = "conduit_bin")] @@ -22,11 +25,11 @@ pub async fn get_capabilities_route() -> ConduitResult/filter/<_>"))] pub async fn get_filter_route() -> ConduitResult { // TODO - Ok(get_filter::Response::new(filter::IncomingFilterDefinition { - event_fields: None, - event_format: None, - account_data: None, - room: None, - presence: None, - }) - .into()) + Ok(get_filter::Response::new(IncomingFilterDefinition::default()).into()) } #[cfg_attr(feature = "conduit_bin", post("/_matrix/client/r0/user/<_>/filter"))] diff --git a/src/client_server/keys.rs b/src/client_server/keys.rs index 58c79da..8426518 100644 --- a/src/client_server/keys.rs +++ b/src/client_server/keys.rs @@ -11,7 +11,7 @@ use ruma::{ uiaa::{AuthFlow, UiaaInfo}, }, }, - encryption::IncomingUnsignedDeviceInfo, + encryption::UnsignedDeviceInfo, }; use std::collections::{BTreeMap, HashSet}; @@ -24,7 +24,7 @@ use rocket::{get, post}; )] pub async fn upload_keys_route( db: State<'_, Database>, - body: Ruma>, + body: Ruma, ) -> ConduitResult { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated"); @@ -94,7 +94,7 @@ pub async fn get_keys_route( Error::bad_database("all_device_keys contained nonexistent device.") })?; - keys.unsigned = IncomingUnsignedDeviceInfo { + keys.unsigned = UnsignedDeviceInfo { device_display_name: metadata.display_name, }; @@ -113,7 +113,7 @@ pub async fn get_keys_route( ), )?; - keys.unsigned = IncomingUnsignedDeviceInfo { + keys.unsigned = UnsignedDeviceInfo { device_display_name: metadata.display_name, }; diff --git a/src/client_server/media.rs b/src/client_server/media.rs index 96874cc..e477d24 100644 --- a/src/client_server/media.rs +++ b/src/client_server/media.rs @@ -39,7 +39,7 @@ pub async fn create_content_route( db.media.create( mxc.clone(), &body.filename.as_deref(), - &body.content_type, + body.content_type.as_deref(), &body.file, )?; @@ -67,7 +67,7 @@ pub async fn get_content_route( Ok(get_content::Response { file, content_type, - content_disposition: filename.unwrap_or_default(), // TODO: Spec says this should be optional + content_disposition: filename, } .into()) } else if &*body.server_name != db.globals.server_name() && body.allow_remote { @@ -84,8 +84,8 @@ pub async fn get_content_route( db.media.create( mxc, - &Some(&get_content_response.content_disposition), - &get_content_response.content_type, + &get_content_response.content_disposition.as_deref(), + get_content_response.content_type.as_deref(), &get_content_response.file, )?; @@ -135,7 +135,7 @@ pub async fn get_content_thumbnail_route( db.media.upload_thumbnail( mxc, &None, - &get_thumbnail_response.content_type, + get_thumbnail_response.content_type.as_deref(), body.width.try_into().expect("all UInts are valid u32s"), body.height.try_into().expect("all UInts are valid u32s"), &get_thumbnail_response.file, diff --git a/src/client_server/membership.rs b/src/client_server/membership.rs index d79079d..180ad69 100644 --- a/src/client_server/membership.rs +++ b/src/client_server/membership.rs @@ -17,13 +17,14 @@ use ruma::{ }, federation, }, - events::pdu::Pdu, - events::{room::member, EventType}, + events::{pdu::Pdu, room::member, EventType}, EventId, Raw, RoomId, RoomVersionId, ServerName, UserId, }; use state_res::StateEvent; use std::{ - collections::BTreeMap, collections::HashMap, collections::HashSet, convert::TryFrom, iter, + collections::{BTreeMap, HashMap, HashSet}, + convert::{TryFrom, TryInto}, + iter, sync::Arc, }; @@ -471,6 +472,10 @@ async fn join_room_by_id_helper( let (make_join_response, remote_server) = make_join_response_and_server?; + let room_version = make_join_response + .room_version + .unwrap_or(RoomVersionId::Version2); + let mut join_event_stub_value = serde_json::from_str::(make_join_response.event.json().get()) .map_err(|_| { @@ -507,8 +512,16 @@ async fn join_room_by_id_helper( // Generate event id let event_id = EventId::try_from(&*format!( "${}", - ruma::signatures::reference_hash(&join_event_stub_value) - .expect("ruma can calculate reference hashes") + ruma::signatures::reference_hash( + &join_event_stub_value + .try_into() + .map_err(|_| Error::BadRequest( + ErrorKind::InvalidParam, + "Join event is not valid json." + ))?, + &room_version + ) + .expect("ruma can calculate reference hashes") )) .expect("ruma's reference hashes are valid event ids"); @@ -520,6 +533,7 @@ async fn join_room_by_id_helper( db.globals.server_name().as_str(), db.globals.keypair(), &mut join_event_stub_value, + &room_version, ) .expect("event is valid, we just created it"); @@ -542,11 +556,11 @@ async fn join_room_by_id_helper( .await?; let add_event_id = |pdu: &Raw| { - let mut value = serde_json::from_str(pdu.json().get()) + let mut value = serde_json::from_str::(pdu.json().get()) .expect("converting raw jsons to values always works"); let event_id = EventId::try_from(&*format!( "${}", - ruma::signatures::reference_hash(&value) + ruma::signatures::reference_hash(&value, &room_version) .expect("ruma can calculate reference hashes") )) .expect("ruma's reference hashes are valid event ids"); diff --git a/src/client_server/state.rs b/src/client_server/state.rs index dbc7fdd..00bc19e 100644 --- a/src/client_server/state.rs +++ b/src/client_server/state.rs @@ -99,7 +99,7 @@ pub async fn send_state_event_for_empty_key_route( )] pub async fn get_state_events_route( db: State<'_, Database>, - body: Ruma, + body: Ruma>, ) -> ConduitResult { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -144,7 +144,7 @@ pub async fn get_state_events_route( )] pub async fn get_state_events_for_key_route( db: State<'_, Database>, - body: Ruma, + body: Ruma>, ) -> ConduitResult { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -194,7 +194,7 @@ pub async fn get_state_events_for_key_route( )] pub async fn get_state_events_for_empty_key_route( db: State<'_, Database>, - body: Ruma, + body: Ruma>, ) -> ConduitResult { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); diff --git a/src/database/media.rs b/src/database/media.rs index 3ecf4bd..4762a42 100644 --- a/src/database/media.rs +++ b/src/database/media.rs @@ -5,7 +5,7 @@ use std::mem; pub struct FileMeta { pub filename: Option, - pub content_type: String, + pub content_type: Option, pub file: Vec, } @@ -19,7 +19,7 @@ impl Media { &self, mxc: String, filename: &Option<&str>, - content_type: &str, + content_type: Option<&str>, file: &[u8], ) -> Result<()> { let mut key = mxc.as_bytes().to_vec(); @@ -29,7 +29,7 @@ impl Media { key.push(0xff); key.extend_from_slice(filename.as_ref().map(|f| f.as_bytes()).unwrap_or_default()); key.push(0xff); - key.extend_from_slice(content_type.as_bytes()); + key.extend_from_slice(content_type.map(|c| c.as_bytes()).unwrap_or(&[])); self.mediaid_file.insert(key, file)?; @@ -41,7 +41,7 @@ impl Media { &self, mxc: String, filename: &Option, - content_type: &str, + content_type: Option<&str>, width: u32, height: u32, file: &[u8], @@ -53,7 +53,7 @@ impl Media { key.push(0xff); key.extend_from_slice(filename.as_ref().map(|f| f.as_bytes()).unwrap_or_default()); key.push(0xff); - key.extend_from_slice(content_type.as_bytes()); + key.extend_from_slice(content_type.map(|c| c.as_bytes()).unwrap_or(&[])); self.mediaid_file.insert(key, file)?; @@ -72,12 +72,17 @@ impl Media { let (key, file) = r?; let mut parts = key.rsplit(|&b| b == 0xff); - let content_type = utils::string_from_bytes( - parts - .next() - .ok_or_else(|| Error::bad_database("Media ID in db is invalid."))?, - ) - .map_err(|_| Error::bad_database("Content type in mediaid_file is invalid unicode."))?; + let content_type = parts + .next() + .ok_or_else(|| Error::bad_database("Media ID in db is invalid."))?; + + let content_type_parsed = if content_type.is_empty() { + None + } else { + Some(utils::string_from_bytes(content_type).map_err(|_| { + Error::bad_database("Content type in mediaid_file is invalid unicode.") + })?) + }; let filename_bytes = parts .next() @@ -93,7 +98,7 @@ impl Media { Ok(Some(FileMeta { filename, - content_type, + content_type: content_type_parsed, file: file.to_vec(), })) } else { @@ -147,12 +152,17 @@ impl Media { let (key, file) = r?; let mut parts = key.rsplit(|&b| b == 0xff); - let content_type = utils::string_from_bytes( - parts - .next() - .ok_or_else(|| Error::bad_database("Invalid Media ID in db"))?, - ) - .map_err(|_| Error::bad_database("Content type in mediaid_file is invalid unicode."))?; + let content_type = parts + .next() + .ok_or_else(|| Error::bad_database("Media ID in db is invalid."))?; + + let content_type_parsed = if content_type.is_empty() { + None + } else { + Some(utils::string_from_bytes(content_type).map_err(|_| { + Error::bad_database("Content type in mediaid_file is invalid unicode.") + })?) + }; let filename_bytes = parts .next() @@ -169,7 +179,7 @@ impl Media { Ok(Some(FileMeta { filename, - content_type, + content_type: content_type_parsed, file: file.to_vec(), })) } else if let Some(r) = self.mediaid_file.scan_prefix(&original_prefix).next() { @@ -178,12 +188,17 @@ impl Media { let (key, file) = r?; let mut parts = key.rsplit(|&b| b == 0xff); - let content_type = utils::string_from_bytes( - parts - .next() - .ok_or_else(|| Error::bad_database("Media ID in db is invalid."))?, - ) - .map_err(|_| Error::bad_database("Content type in mediaid_file is invalid unicode."))?; + let content_type = parts + .next() + .ok_or_else(|| Error::bad_database("Media ID in db is invalid."))?; + + let content_type_parsed = if content_type.is_empty() { + None + } else { + Some(utils::string_from_bytes(content_type).map_err(|_| { + Error::bad_database("Content type in mediaid_file is invalid unicode.") + })?) + }; let filename_bytes = parts .next() @@ -269,7 +284,7 @@ impl Media { Ok(Some(FileMeta { filename, - content_type, + content_type: content_type_parsed, file: thumbnail_bytes.to_vec(), })) } else { diff --git a/src/database/rooms.rs b/src/database/rooms.rs index 05abe03..0fde4c2 100644 --- a/src/database/rooms.rs +++ b/src/database/rooms.rs @@ -15,7 +15,7 @@ use ruma::{ }, EventType, }, - EventId, Raw, RoomAliasId, RoomId, ServerName, UserId, + EventId, Raw, RoomAliasId, RoomId, RoomVersionId, ServerName, UserId, }; use sled::IVec; use state_res::{event_auth, Error as StateError, Requester, StateEvent, StateMap, StateStore}; @@ -815,13 +815,14 @@ impl Rooms { globals.server_name().as_str(), globals.keypair(), &mut pdu_json, + &RoomVersionId::Version6, ) .expect("event is valid, we just created it"); // Generate event id pdu.event_id = EventId::try_from(&*format!( "${}", - ruma::signatures::reference_hash(&pdu_json) + ruma::signatures::reference_hash(&pdu_json, &RoomVersionId::Version6) .expect("ruma can calculate reference hashes") )) .expect("ruma's reference hashes are valid event ids"); diff --git a/src/database/users.rs b/src/database/users.rs index 0d35e36..01eb686 100644 --- a/src/database/users.rs +++ b/src/database/users.rs @@ -8,7 +8,7 @@ use ruma::{ keys::{CrossSigningKey, OneTimeKey}, }, }, - encryption::IncomingDeviceKeys, + encryption::DeviceKeys, events::{AnyToDeviceEvent, EventType}, DeviceId, DeviceKeyAlgorithm, DeviceKeyId, Raw, UserId, }; @@ -400,7 +400,7 @@ impl Users { &self, user_id: &UserId, device_id: &DeviceId, - device_keys: &IncomingDeviceKeys, + device_keys: &DeviceKeys, rooms: &super::rooms::Rooms, globals: &super::globals::Globals, ) -> Result<()> { @@ -630,7 +630,7 @@ impl Users { &self, user_id: &UserId, device_id: &DeviceId, - ) -> Result> { + ) -> Result> { let mut key = user_id.to_string().as_bytes().to_vec(); key.push(0xff); key.extend_from_slice(device_id.as_bytes()); diff --git a/src/pdu.rs b/src/pdu.rs index 7118bfc..1b38ea3 100644 --- a/src/pdu.rs +++ b/src/pdu.rs @@ -199,9 +199,7 @@ impl PduEvent { serde_json::from_value(json).expect("Raw::from_value always works") } - pub fn convert_to_outgoing_federation_event( - mut pdu_json: serde_json::Value, - ) -> Raw { + pub fn convert_to_outgoing_federation_event(mut pdu_json: serde_json::Value) -> Raw { if let Some(unsigned) = pdu_json .as_object_mut() .expect("json is object") diff --git a/src/ruma_wrapper.rs b/src/ruma_wrapper.rs index 7722a42..4eef681 100644 --- a/src/ruma_wrapper.rs +++ b/src/ruma_wrapper.rs @@ -1,7 +1,9 @@ use crate::Error; use ruma::{ - api::{Outgoing, OutgoingRequest}, + api::AuthScheme, + api::OutgoingRequest, identifiers::{DeviceId, UserId}, + Outgoing, }; use std::{convert::TryFrom, convert::TryInto, ops::Deref}; @@ -61,27 +63,30 @@ where .await .expect("database was loaded"); - let (sender_user, sender_device) = if T::METADATA.requires_authentication { - // Get token from header or query value - let token = match request - .headers() - .get_one("Authorization") - .map(|s| s[7..].to_owned()) // Split off "Bearer " - .or_else(|| request.get_query_value("access_token").and_then(|r| r.ok())) - { - // TODO: M_MISSING_TOKEN - None => return Failure((Status::Unauthorized, ())), - Some(token) => token, - }; - - // Check if token is valid - match db.users.find_from_token(&token).unwrap() { - // TODO: M_UNKNOWN_TOKEN - None => return Failure((Status::Unauthorized, ())), - Some((user_id, device_id)) => (Some(user_id), Some(device_id.into())), + let (sender_user, sender_device) = match T::METADATA.authentication { + AuthScheme::AccessToken => { + // Get token from header or query value + let token = match request + .headers() + .get_one("Authorization") + .map(|s| s[7..].to_owned()) // Split off "Bearer " + .or_else(|| request.get_query_value("access_token").and_then(|r| r.ok())) + { + // TODO: M_MISSING_TOKEN + None => return Failure((Status::Unauthorized, ())), + Some(token) => token, + }; + + // Check if token is valid + match db.users.find_from_token(&token).unwrap() { + // TODO: M_UNKNOWN_TOKEN + None => return Failure((Status::Unauthorized, ())), + Some((user_id, device_id)) => (Some(user_id), Some(device_id.into())), + } } - } else { - (None, None) + AuthScheme::None => (None, None), + AuthScheme::ServerSignatures => (None, None), + AuthScheme::QueryOnlyAccessToken => (None, None), }; let mut http_request = http::Request::builder() diff --git a/src/server_server.rs b/src/server_server.rs index ccb1399..701fa93 100644 --- a/src/server_server.rs +++ b/src/server_server.rs @@ -17,7 +17,7 @@ use ruma::{ OutgoingRequest, }, directory::{IncomingFilter, IncomingRoomNetwork}, - EventId, ServerName, + EventId, RoomVersionId, ServerName, }; use std::{ collections::BTreeMap, @@ -375,12 +375,13 @@ pub fn send_transaction_message_route<'a>( //dbg!(&*body); for pdu in &body.pdus { - let mut value = serde_json::from_str(pdu.json().get()) + let mut value = serde_json::from_str::(pdu.json().get()) .expect("converting raw jsons to values always works"); let event_id = EventId::try_from(&*format!( "${}", - ruma::signatures::reference_hash(&value).expect("ruma can calculate reference hashes") + ruma::signatures::reference_hash(&value, &RoomVersionId::Version6) + .expect("ruma can calculate reference hashes") )) .expect("ruma's reference hashes are valid event ids");