diff --git a/configs/client_config.toml b/configs/client_config.toml index d379fba..8c6b224 100644 --- a/configs/client_config.toml +++ b/configs/client_config.toml @@ -1,3 +1,4 @@ [client_config] server_address = "127.0.0.1:2026" server_name = "localhost" +server_fingerprint = "" diff --git a/configs/server_config.example.toml b/configs/server_config.example.toml index 179d6e5..a582f7a 100644 --- a/configs/server_config.example.toml +++ b/configs/server_config.example.toml @@ -1,3 +1,5 @@ [server_config] database_path = "yumush.db" server_address = "127.0.0.1:2026" +certificate_path = "server_certificate.der" +key_path = "server_key.der" diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index e95c430..d91c51d 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -9,6 +9,8 @@ tokio.workspace = true quinn = { workspace = true, features = ["rustls-ring"] } gpui-kit = "0.7.0" +tracing = "0.1.44" +tracing-subscriber = "0.3.23" [lints] workspace = true diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index 6885e1e..aa88458 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -1,5 +1,4 @@ use std::fmt::Display; -use std::time::Duration; use common::model::User; use gpui_kit::{ @@ -20,8 +19,6 @@ mod chat; use auth::Auth; use chat::Chat; -const CHECK_INTERVAL: Duration = Duration::from_secs(3); - #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Route { Login, @@ -68,43 +65,17 @@ impl Yumush { } } - fn start_polling(&self, window: &mut Window, cx: &mut Context) { - cx.spawn_in(window, async move |this, cx| { - loop { - cx.background_executor().timer(CHECK_INTERVAL).await; - - let keep_going = this.update_in(cx, |yumush, window, cx| { - if yumush.user.is_none() { - return false; - } - - if yumush.connected { - yumush.get_chat_users(window, cx); - yumush.get_communities(window, cx); - } - - true - }); - - if !matches!(keep_going, Ok(true)) { - break; - } - } - }) - .detach(); - } - fn logout(&mut self, window: &mut Window, cx: &mut Context) { - let Some(user) = self.user.take() else { + if self.user.take().is_none() { return; - }; + } let network = self.network.clone(); self.chat.reset(); self.change_page(Route::Login, window, cx); cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.deauthenticate(&user.username).await { + if let Err(error) = network.logout().await { notify_error(&this, cx, error); } }) @@ -128,21 +99,19 @@ impl Yumush { cx: &mut Context, ) { match event { - NetworkEvent::Connected(user) => { + NetworkEvent::Connected => { self.connected = true; - match user { - Some(user) => self.user = Some(user), - None if self.user.is_some() => { - self.user = None; - self.change_page(Route::Login, window, cx); - } - None => {} + if self.user.is_some() { + self.reload(window, cx); } } - NetworkEvent::ConnectionFailed(_) | NetworkEvent::Disconnected(_) => { - self.connected = false; + NetworkEvent::Disconnected(_) => self.connected = false, + NetworkEvent::SessionLost => { + self.user = None; + self.chat.reset(); + self.change_page(Route::Login, window, cx); } - NetworkEvent::MessageReceived(message) => self.chat.merge_messages(vec![message]), + NetworkEvent::Pushed(event) => self.chat.apply_event(event), } cx.notify(); diff --git a/crates/client/src/gui/auth.rs b/crates/client/src/gui/auth.rs index 55a6b10..9c44976 100644 --- a/crates/client/src/gui/auth.rs +++ b/crates/client/src/gui/auth.rs @@ -11,21 +11,29 @@ use crate::gui::{Route, Yumush, new_input, notify_error}; pub struct Auth { username_input: Entity, + password_input: Entity, } impl Auth { pub fn new(window: &mut Window, cx: &mut Context) -> Self { let username_input = new_input("Username...", window, cx); + let password_input = new_input("Password...", window, cx); + password_input.update(cx, |input, cx| input.set_masked(true, window, cx)); username_input.update(cx, |input, cx| input.focus(window, cx)); - cx.subscribe_in(&username_input, window, |this, _, event, window, cx| { - if matches!(event, InputEvent::PressEnter { .. }) { - submit(this, window, cx); - } - }) - .detach(); + for input in [&username_input, &password_input] { + cx.subscribe_in(input, window, |this, _, event, window, cx| { + if matches!(event, InputEvent::PressEnter { .. }) { + submit(this, window, cx); + } + }) + .detach(); + } - Self { username_input } + Self { + username_input, + password_input, + } } pub fn focus(&self, window: &mut Window, cx: &mut Context) { @@ -36,21 +44,26 @@ impl Auth { fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context) { let username = this.auth.username_input.read(cx).text().to_string(); + let password = this.auth.password_input.read(cx).text().to_string(); let route = this.current_route; let network = this.network.clone(); cx.spawn_in(window, async move |this, cx| { let result = match route { - Route::Register => network.create_user(&username).await, - _ => network.authenticate(&username).await, + Route::Register => network.register(&username, &password).await, + _ => network.login(&username, &password).await, }; match result { Ok(user) => { let _ = this.update_in(cx, |yumush, window, cx| { + yumush + .auth + .password_input + .update(cx, |input, cx| input.set_value("", window, cx)); yumush.user = Some(user); yumush.change_page(Route::Chat, window, cx); - yumush.start_polling(window, cx); + yumush.load_communities(window, cx); }); } Err(error) => notify_error(&this, cx, error), @@ -85,6 +98,8 @@ impl Yumush { .w_1_5() .child("Username") .child(Input::new(&self.auth.username_input)) + .child("Password") + .child(Input::new(&self.auth.password_input)) .child(action_button) .child(switch_button) } diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index 3d4763f..37438f7 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -1,5 +1,6 @@ use common::{ - constant::NEWEST_MESSAGE_MARKER, + constant::MESSAGE_PAGE_LIMIT, + event::Event, model::{Community, Message, User}, validate::{validate_community_name, validate_message_body}, }; @@ -24,11 +25,28 @@ enum Panel { Join, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum History { + More, + End, +} + +impl History { + fn of_page(length: usize) -> Self { + if length < MESSAGE_PAGE_LIMIT { + History::End + } else { + History::More + } + } +} + pub struct Chat { communities: Vec, selected_community_id: Option, - users: Vec, + members: Vec, messages: Vec, + history: History, panel: Panel, message_input: Entity, community_name_input: Entity, @@ -73,8 +91,9 @@ impl Chat { Self { communities: vec![], selected_community_id: None, - users: vec![], + members: vec![], messages: vec![], + history: History::End, panel: Panel::None, message_input, community_name_input, @@ -88,10 +107,92 @@ impl Chat { .update(cx, |input, cx| input.focus(window, cx)); } - pub fn merge_messages(&mut self, messages: Vec) { - self.messages.extend(messages); + pub fn apply_event(&mut self, event: Event) { + match event { + Event::MessageCreated(message) | Event::MessageUpdated(message) => { + if self.is_selected(&message.community_id) { + self.insert_messages([message]); + } + } + Event::MessageDeleted(message) => { + if self.is_selected(&message.community_id) { + self.messages.retain(|existing| existing.id != message.id); + } + } + Event::MemberJoined { community_id, user } => { + if self.is_selected(&community_id) { + self.insert_member(user); + } + } + Event::MemberLeft { + community_id, + user_id, + } => { + if self.is_selected(&community_id) { + self.members.retain(|member| member.id != user_id); + } + } + Event::CommunityUpdated(community) => self.insert_community(community), + Event::CommunityDeleted { community_id } => self.remove_community(&community_id), + } + } + + fn is_selected(&self, community_id: &str) -> bool { + self.selected_community_id.as_deref() == Some(community_id) + } + + fn select(&mut self, community_id: Option) { + self.selected_community_id = community_id; + self.members.clear(); + self.messages.clear(); + self.history = History::End; + } + + fn insert_messages(&mut self, messages: impl IntoIterator) { + for message in messages { + self.messages.retain(|existing| existing.id != message.id); + self.messages.push(message); + } self.messages.sort_by(|left, right| left.id.cmp(&right.id)); - self.messages.dedup_by(|left, right| left.id == right.id); + } + + fn add_page(&mut self, page: Vec) { + self.history = History::of_page(page.len()); + self.insert_messages(page); + } + + fn insert_member(&mut self, user: User) { + self.members.retain(|member| member.id != user.id); + self.members.push(user); + self.members.sort_by(|left, right| left.id.cmp(&right.id)); + } + + fn insert_community(&mut self, community: Community) { + self.communities + .retain(|existing| existing.id != community.id); + self.communities.push(community); + self.communities + .sort_by(|left, right| left.id.cmp(&right.id)); + } + + fn remove_community(&mut self, community_id: &str) { + self.communities + .retain(|community| community.id != community_id); + if self.is_selected(community_id) { + self.select(None); + } + } + + fn replace_communities(&mut self, communities: Vec) { + self.communities = communities; + + let selected_present = self + .communities + .iter() + .any(|community| self.is_selected(&community.id)); + if !selected_present { + self.select(None); + } } fn set_panel(&mut self, panel: Panel) { @@ -103,9 +204,7 @@ impl Chat { pub fn reset(&mut self) { self.communities.clear(); - self.selected_community_id = None; - self.users.clear(); - self.messages.clear(); + self.select(None); self.set_panel(Panel::None); } } @@ -123,9 +222,6 @@ fn send_message( return; } - let Some(user_id) = this.user.as_ref().map(|user| user.id.clone()) else { - return; - }; let Some(community_id) = this.chat.selected_community_id.clone() else { window.push_notification(Notification::error("No Community Selected"), cx); return; @@ -133,7 +229,7 @@ fn send_message( let network = this.network.clone(); cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.create_message(&user_id, &community_id, &body).await { + if let Err(error) = network.create_message(&community_id, &body).await { notify_error(&this, cx, error); } }) @@ -157,7 +253,6 @@ fn create_community( let network = this.network.clone(); input.update(cx, |state, cx| state.set_value("", window, cx)); - this.chat.set_panel(Panel::None); cx.spawn_in(window, async move |this, cx| { let community = match network.create_community(&name).await { @@ -169,8 +264,7 @@ fn create_community( }; let _ = this.update_in(cx, |yumush, window, cx| { - yumush.get_communities(window, cx); - yumush.select_community(community.id, window, cx); + yumush.enter_community(community, window, cx); }); }) .detach(); @@ -223,7 +317,7 @@ impl Yumush { .flex_col() .flex_1() .min_w_0() - .child(self.message_list()) + .child(self.message_list(&entity)) .child( div() .p_2() @@ -232,7 +326,7 @@ impl Yumush { .child(Input::new(&self.chat.message_input)), ), ) - .child(self.user_list()) + .child(self.member_list(&entity)) } fn community_list(&self, entity: &Entity) -> impl IntoElement { @@ -318,8 +412,7 @@ impl Yumush { .enumerate() .map(|(index, community)| { let community_id = community.id.clone(); - let selected = self.chat.selected_community_id.as_deref() - == Some(community.id.as_str()); + let selected = self.chat.is_selected(&community.id); let entity = entity.clone(); div() @@ -341,7 +434,7 @@ impl Yumush { ) } - fn message_list(&self) -> impl IntoElement { + fn message_list(&self, entity: &Entity) -> impl IntoElement { div() .id("chat_messages") .flex() @@ -351,20 +444,18 @@ impl Yumush { .overflow_y_scroll() .p_2() .gap_1() + .children((self.chat.history == History::More).then(|| older_button(entity))) .children( self.chat .messages .iter() - .filter(|message| { - Some(&message.community_id) == self.chat.selected_community_id.as_ref() - }) - .map(|message| render_message(message, &self.chat.users)), + .map(|message| render_message(message, &self.chat.members)), ) } - fn user_list(&self) -> impl IntoElement { + fn member_list(&self, entity: &Entity) -> impl IntoElement { div() - .id("user_list") + .id("member_list") .h_full() .flex() .flex_col() @@ -377,13 +468,26 @@ impl Yumush { .gap_1() .child( div() - .text_color(rgb(0x949ba4)) - .font_weight(FontWeight::SEMIBOLD) - .child(format!("Online - {}", self.chat.users.len())), + .flex() + .flex_row() + .items_center() + .justify_between() + .child( + div() + .text_color(rgb(0x949ba4)) + .font_weight(FontWeight::SEMIBOLD) + .child(format!("Members - {}", self.chat.members.len())), + ) + .children( + self.chat + .selected_community_id + .is_some() + .then(|| leave_button(entity)), + ), ) .children( self.chat - .users + .members .iter() .map(|user| div().p_1().child(user.username.clone())), ) @@ -415,55 +519,73 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - self.chat.selected_community_id = Some(community_id); - self.chat.users.clear(); - self.get_chat_users(window, cx); - self.get_chat_messages(window, cx); + self.chat.select(Some(community_id)); + self.load_members(window, cx); + self.load_latest_messages(window, cx); cx.notify(); } - pub(super) fn get_chat_users(&self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { - return; - }; + fn enter_community( + &mut self, + community: Community, + window: &mut Window, + cx: &mut Context, + ) { + self.chat.set_panel(Panel::None); + let community_id = community.id.clone(); + self.chat.insert_community(community); + self.select_community(community_id, window, cx); + } + + pub(super) fn reload(&self, window: &mut Window, cx: &mut Context) { + self.load_communities(window, cx); + + if self.chat.selected_community_id.is_some() { + self.load_members(window, cx); + self.load_latest_messages(window, cx); + } + } + + pub(super) fn load_communities(&self, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let user_ids = match network.users_in(&community_id).await { - Ok(user_ids) => user_ids, + let communities = match network.communities().await { + Ok(communities) => communities, Err(error) => { notify_error(&this, cx, error); return; } }; - let mut users = Vec::with_capacity(user_ids.len()); - for user_id in &user_ids { - if let Ok(user) = network.read_user(user_id).await { - users.push(user); - } - } + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.chat.replace_communities(communities); - let _ = this.update(cx, |yumush, cx| { - yumush.chat.users = users; + if yumush.chat.selected_community_id.is_none() { + let first = yumush + .chat + .communities + .first() + .map(|community| community.id.clone()); + if let Some(community_id) = first { + yumush.select_community(community_id, window, cx); + } + } cx.notify(); }); }) .detach(); } - pub(super) fn get_chat_messages(&self, window: &mut Window, cx: &mut Context) { + fn load_members(&self, window: &mut Window, cx: &mut Context) { let Some(community_id) = self.chat.selected_community_id.clone() else { return; }; let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let messages = match network - .read_messages(&community_id, NEWEST_MESSAGE_MARKER) - .await - { - Ok(messages) => messages, + let members = match network.members(&community_id).await { + Ok(members) => members, Err(error) => { notify_error(&this, cx, error); return; @@ -471,64 +593,86 @@ impl Yumush { }; let _ = this.update(cx, |yumush, cx| { - yumush.chat.merge_messages(messages); - cx.notify(); + if yumush.chat.is_selected(&community_id) { + yumush.chat.members = members; + cx.notify(); + } }); }) .detach(); } - pub(super) fn get_communities(&self, window: &mut Window, cx: &mut Context) { - let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else { + fn load_latest_messages(&self, window: &mut Window, cx: &mut Context) { + self.load_messages(None, window, cx); + } + + fn load_older_messages(&self, window: &mut Window, cx: &mut Context) { + let Some(oldest_id) = self.chat.messages.first().map(|message| message.id.clone()) else { + return; + }; + self.load_messages(Some(oldest_id), window, cx); + } + + fn load_messages(&self, before: Option, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { return; }; let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let community_ids = match network.communities_of(&user_id).await { - Ok(community_ids) => community_ids, + let page = match network + .read_messages(&community_id, before.as_deref()) + .await + { + Ok(page) => page, Err(error) => { notify_error(&this, cx, error); return; } }; - let mut communities = Vec::with_capacity(community_ids.len()); - for community_id in community_ids { - if let Ok(community) = network.read_community(&community_id).await { - communities.push(community); - } - } - let _ = this.update(cx, |yumush, cx| { - if yumush.chat.selected_community_id.is_none() { - yumush.chat.selected_community_id = - communities.first().map(|community| community.id.clone()); + if yumush.chat.is_selected(&community_id) { + yumush.chat.add_page(page); + cx.notify(); } - yumush.chat.communities = communities; - cx.notify(); }); }) .detach(); } fn join_community(&self, community_id: &str, window: &mut Window, cx: &mut Context) { - let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else { + let network = self.network.clone(); + let community_id = community_id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.join_community(&community_id).await { + Ok(community) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.enter_community(community, window, cx); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + fn leave_community(&self, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { return; }; let network = self.network.clone(); - let community_id = community_id.to_string(); cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.join_community(&user_id, &community_id).await { + if let Err(error) = network.leave_community(&community_id).await { notify_error(&this, cx, error); return; } - let _ = this.update_in(cx, |yumush, window, cx| { - yumush.chat.set_panel(Panel::None); - yumush.get_communities(window, cx); - yumush.select_community(community_id, window, cx); + let _ = this.update(cx, |yumush, cx| { + yumush.chat.remove_community(&community_id); + cx.notify(); }); }) .detach(); @@ -548,8 +692,28 @@ fn panel_button( }) } -fn render_message(message: &Message, users: &[User]) -> impl IntoElement { - let username = users +fn leave_button(entity: &Entity) -> impl IntoElement { + let entity = entity.clone(); + + Button::new("leave_community_button") + .label("Leave") + .on_click(move |_, window, cx| { + entity.update(cx, |yumush, cx| yumush.leave_community(window, cx)); + }) +} + +fn older_button(entity: &Entity) -> impl IntoElement { + let entity = entity.clone(); + + Button::new("load_older_button") + .label("↑") + .on_click(move |_, window, cx| { + entity.update(cx, |yumush, cx| yumush.load_older_messages(window, cx)); + }) +} + +fn render_message(message: &Message, members: &[User]) -> impl IntoElement { + let username = members .iter() .find(|user| user.id == message.user_id) .map(|user| user.username.as_str()) diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index abf8dca..892d0bd 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -1,4 +1,4 @@ -use common::config::parse; +use common::config::Config; pub mod gui; pub mod network; @@ -11,17 +11,19 @@ const CLIENT_CONFIG_FILE_CONTENT: &str = include_str!(concat!( )); pub struct ClientConfig { - server_address: String, - server_name: String, + pub server_address: String, + pub server_name: String, + pub server_fingerprint: String, } impl Default for ClientConfig { fn default() -> Self { - let fields = parse(CLIENT_CONFIG_FILE_CONTENT).expect("client config"); + let config = Config::parse(CLIENT_CONFIG_FILE_CONTENT).expect("client config"); Self { - server_address: fields["server_address"].clone(), - server_name: fields["server_name"].clone(), + server_address: config.get("server_address").expect("server_address"), + server_name: config.get("server_name").expect("server_name"), + server_fingerprint: config.get("server_fingerprint").expect("server_fingerprint"), } } } diff --git a/crates/client/src/main.rs b/crates/client/src/main.rs index c8704c9..7ee7424 100644 --- a/crates/client/src/main.rs +++ b/crates/client/src/main.rs @@ -5,6 +5,8 @@ use gpui_kit::{ }; fn main() { + tracing_subscriber::fmt().with_max_level(tracing::Level::INFO).init(); + let (network_handle, network_event_receiver) = network::start(ClientConfig::default()); application().run(|cx: &mut App| { diff --git a/crates/client/src/network.rs b/crates/client/src/network.rs index 630ef27..a957df6 100644 --- a/crates/client/src/network.rs +++ b/crates/client/src/network.rs @@ -2,13 +2,15 @@ use std::sync::Arc; use std::time::Duration; use common::{ - constant::MESSAGE_PAGE_LIMIT, error::Error, + event::Event, model::{Community, Message, User}, - network::{receive_message, send_request}, + network::{receive_event, send_request}, request::Request, response::Response, - validate::{validate_community_name, validate_message_body, validate_username}, + validate::{ + validate_community_name, validate_message_body, validate_password, validate_username, + }, }; use quinn::{ Endpoint, @@ -19,6 +21,7 @@ use quinn::{ }, }; use tokio::sync::{mpsc, oneshot}; +use tracing::{info, warn}; use crate::ClientConfig; @@ -30,10 +33,10 @@ const RECONNECT_DELAY: Duration = Duration::from_secs(1); #[derive(Debug)] pub enum NetworkEvent { - Connected(Option), - ConnectionFailed(Error), + Connected, Disconnected(Error), - MessageReceived(Message), + SessionLost, + Pushed(Event), } #[derive(Debug)] @@ -62,40 +65,38 @@ impl NetworkHandle { } } - pub async fn authenticate(&self, token: &str) -> Result { - match self - .request(Request::Authentication { - token: token.to_string(), - }) - .await? - { - Response::Authentication(user) => Ok(user), + async fn sign_in(&self, request: Request) -> Result { + match self.request(request).await? { + Response::Session { user, .. } => Ok(user), _ => Err(Error::Server), } } - pub async fn deauthenticate(&self, token: &str) -> Result { - match self - .request(Request::Deauthentication { - token: token.to_string(), - }) - .await? - { - Response::Deauthentication(user) => Ok(user), - _ => Err(Error::Server), - } + pub async fn register(&self, username: &str, password: &str) -> Result { + validate_username(username)?; + validate_password(password)?; + + self.sign_in(Request::Register { + username: username.to_string(), + password: password.to_string(), + }) + .await } - pub async fn create_user(&self, username: &str) -> Result { + pub async fn login(&self, username: &str, password: &str) -> Result { validate_username(username)?; + validate_password(password)?; - match self - .request(Request::CreateUser { - username: username.to_string(), - }) - .await? - { - Response::CreateUser(user) => Ok(user), + self.sign_in(Request::Login { + username: username.to_string(), + password: password.to_string(), + }) + .await + } + + pub async fn logout(&self) -> Result<(), Error> { + match self.request(Request::Logout).await? { + Response::Done => Ok(()), _ => Err(Error::Server), } } @@ -107,7 +108,7 @@ impl NetworkHandle { }) .await? { - Response::ReadUser(user) => Ok(user), + Response::User(user) => Ok(user), _ => Err(Error::Server), } } @@ -121,109 +122,96 @@ impl NetworkHandle { }) .await? { - Response::CreateCommunity(community) => Ok(community), + Response::Community(community) => Ok(community), _ => Err(Error::Server), } } - pub async fn read_community(&self, community_id: &str) -> Result { + pub async fn join_community(&self, community_id: &str) -> Result { match self - .request(Request::ReadCommunity { + .request(Request::JoinCommunity { community_id: community_id.to_string(), }) .await? { - Response::ReadCommunity(community) => Ok(community), + Response::Community(community) => Ok(community), _ => Err(Error::Server), } } - pub async fn create_message( - &self, - user_id: &str, - community_id: &str, - body: &str, - ) -> Result { - validate_message_body(body)?; - + pub async fn leave_community(&self, community_id: &str) -> Result<(), Error> { match self - .request(Request::CreateMessage { - user_id: user_id.to_string(), + .request(Request::LeaveCommunity { community_id: community_id.to_string(), - body: body.to_string(), }) .await? { - Response::CreateMessage(message) => Ok(message), + Response::Done => Ok(()), _ => Err(Error::Server), } } - pub async fn read_messages( - &self, - community_id: &str, - marker: &str, - ) -> Result, Error> { + pub async fn search_community(&self, name: &str) -> Result, Error> { + validate_community_name(name)?; + match self - .request(Request::ReadMessages { - community_id: community_id.to_string(), - marker: marker.to_string(), - limit: MESSAGE_PAGE_LIMIT, + .request(Request::SearchCommunity { + name: name.to_string(), }) .await? { - Response::ReadMessages(messages) => Ok(messages), + Response::Communities(communities) => Ok(communities), _ => Err(Error::Server), } } - pub async fn join_community(&self, user_id: &str, community_id: &str) -> Result<(), Error> { - match self - .request(Request::JoinCommunity { - user_id: user_id.to_string(), - community_id: community_id.to_string(), - }) - .await? - { - Response::JoinCommunity => Ok(()), + pub async fn communities(&self) -> Result, Error> { + match self.request(Request::Communities).await? { + Response::Communities(communities) => Ok(communities), _ => Err(Error::Server), } } - pub async fn users_in(&self, community_id: &str) -> Result, Error> { + pub async fn members(&self, community_id: &str) -> Result, Error> { match self - .request(Request::UsersIn { + .request(Request::Members { community_id: community_id.to_string(), }) .await? { - Response::UsersIn(user_ids) => Ok(user_ids), + Response::Members(users) => Ok(users), _ => Err(Error::Server), } } - pub async fn communities_of(&self, user_id: &str) -> Result, Error> { + pub async fn create_message(&self, community_id: &str, body: &str) -> Result { + validate_message_body(body)?; + match self - .request(Request::CommunitiesOf { - user_id: user_id.to_string(), + .request(Request::CreateMessage { + community_id: community_id.to_string(), + body: body.to_string(), }) .await? { - Response::CommunitiesOf(community_ids) => Ok(community_ids), + Response::Message(message) => Ok(message), _ => Err(Error::Server), } } - pub async fn search_community(&self, name: &str) -> Result, Error> { - validate_community_name(name)?; - + pub async fn read_messages( + &self, + community_id: &str, + before: Option<&str>, + ) -> Result, Error> { match self - .request(Request::SearchCommunity { - name: name.to_string(), + .request(Request::ReadMessages { + community_id: community_id.to_string(), + before: before.map(str::to_string), }) .await? { - Response::SearchCommunity(communities) => Ok(communities), + Response::Messages(messages) => Ok(messages), _ => Err(Error::Server), } } @@ -247,24 +235,30 @@ pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver Result { +async fn connect(client_config: &ClientConfig) -> Result { let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)?; - endpoint.set_default_client_config(config()); + endpoint.set_default_client_config(config(&client_config.server_fingerprint)); let connection = endpoint - .connect(server_address.parse()?, server_name)? + .connect( + client_config.server_address.parse()?, + &client_config.server_name, + )? .await?; Ok(connection) } -fn config() -> quinn::ClientConfig { +fn config(fingerprint: &str) -> quinn::ClientConfig { let crypto_provider = Arc::new(rustls::crypto::ring::default_provider()); let tls_config = rustls::ClientConfig::builder_with_provider(crypto_provider.clone()) .with_protocol_versions(&[&rustls::version::TLS13]) .unwrap() .dangerous() - .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate(crypto_provider))) + .with_custom_certificate_verifier(Arc::new(PinnedCertificate { + fingerprint: fingerprint.to_string(), + provider: crypto_provider, + })) .with_no_client_auth(); let mut client_config = @@ -297,16 +291,18 @@ async fn actor( mut command_receiver: mpsc::Receiver, event_sender: mpsc::Sender, ) { - let mut authentication_token: Option = None; - let mut authentication_epoch = 0; + let mut token: Option = None; + let mut token_epoch = 0; let (token_sender, mut token_receiver) = mpsc::channel(CHANNEL_SIZE); 'session: loop { let connection = loop { - match connect(&client_config.server_address, &client_config.server_name).await { + match connect(&client_config).await { Ok(connection) => break connection, Err(error) => { + warn!("connect failed: {error}"); + if event_sender - .send(NetworkEvent::ConnectionFailed(error)) + .send(NetworkEvent::Disconnected(error)) .await .is_err() { @@ -318,52 +314,49 @@ async fn actor( }; }; - let mut user = None; - if let Some(token) = &authentication_token { - let request = Request::Authentication { - token: token.clone(), - }; + if let Some(stored) = token.clone() { + let request = Request::Resume { token: stored }; match send(&connection, &request).await { - Ok(Response::Authentication(user_)) => user = Some(user_), - _ => authentication_token = None, + Ok(Response::Session { token: resumed, .. }) => token = Some(resumed), + _ => { + warn!("session resume failed"); + token = None; + + if event_sender.send(NetworkEvent::SessionLost).await.is_err() { + return; + } + } } } - if event_sender - .send(NetworkEvent::Connected(user)) - .await - .is_err() - { + info!("connected"); + if event_sender.send(NetworkEvent::Connected).await.is_err() { return; } - tokio::spawn(message_receive_loop( - connection.clone(), - event_sender.clone(), - )); + tokio::spawn(event_receive_loop(connection.clone(), event_sender.clone())); loop { tokio::select! { command = command_receiver.recv() => match command { Some(Command { request, reply }) => match &request { - Request::Authentication { token } => { - let token = token.clone(); + Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => { let token_sender = token_sender.clone(); - let epoch = authentication_epoch; + let epoch = token_epoch; let connection = connection.clone(); tokio::spawn(async move { let response = send(&connection, &request).await; - if let Ok(Response::Authentication(_)) = &response { - let _ = token_sender.send((epoch, token)).await; + if let Ok(Response::Session { token: session_token, .. }) = &response { + let _ = token_sender.send((epoch, session_token.clone())).await; } let _ = reply.send(response); }); } - Request::Deauthentication { .. } => { - authentication_token = None; - authentication_epoch += 1; + Request::Logout => { + token = None; + token_epoch += 1; tokio::spawn(dispatch(connection.clone(), request, reply)); } @@ -373,13 +366,15 @@ async fn actor( }, None => break 'session, }, - Some((epoch, token)) = token_receiver.recv() => { - if epoch == authentication_epoch { - authentication_token = Some(token); + Some((epoch, session_token)) = token_receiver.recv() => { + if epoch == token_epoch { + token = Some(session_token); } } error = connection.closed() => { + warn!("disconnected: {error}"); + if event_sender.send(NetworkEvent::Disconnected(error.into())).await.is_err() { return; } @@ -391,7 +386,7 @@ async fn actor( } } -async fn message_receive_loop( +async fn event_receive_loop( connection: quinn::Connection, event_sender: mpsc::Sender, ) { @@ -399,9 +394,9 @@ async fn message_receive_loop( return; }; - while let Ok(message) = receive_message(&mut receive_stream).await { + while let Ok(event) = receive_event(&mut receive_stream).await { if event_sender - .send(NetworkEvent::MessageReceived(message)) + .send(NetworkEvent::Pushed(event)) .await .is_err() { @@ -411,18 +406,27 @@ async fn message_receive_loop( } #[derive(Debug)] -struct AcceptAnyCertificate(Arc); +struct PinnedCertificate { + fingerprint: String, + provider: Arc, +} -impl ServerCertVerifier for AcceptAnyCertificate { +impl ServerCertVerifier for PinnedCertificate { fn verify_server_cert( &self, - _end_entity: &rustls::pki_types::CertificateDer<'_>, + end_entity: &rustls::pki_types::CertificateDer<'_>, _intermediates: &[rustls::pki_types::CertificateDer<'_>], _server_name: &rustls::pki_types::ServerName<'_>, _ocsp_response: &[u8], _now: rustls::pki_types::UnixTime, - ) -> Result { - Ok(ServerCertVerified::assertion()) + ) -> Result { + if common::certificate::fingerprint(end_entity) == self.fingerprint { + Ok(ServerCertVerified::assertion()) + } else { + Err(rustls::Error::General( + "certificate fingerprint mismatch".to_string(), + )) + } } fn verify_tls12_signature( @@ -435,7 +439,7 @@ impl ServerCertVerifier for AcceptAnyCertificate { message, cert, dss, - &self.0.signature_verification_algorithms, + &self.provider.signature_verification_algorithms, ) } @@ -449,11 +453,13 @@ impl ServerCertVerifier for AcceptAnyCertificate { message, cert, dss, - &self.0.signature_verification_algorithms, + &self.provider.signature_verification_algorithms, ) } fn supported_verify_schemes(&self) -> Vec { - self.0.signature_verification_algorithms.supported_schemes() + self.provider + .signature_verification_algorithms + .supported_schemes() } } diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index c015136..fe6d972 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -6,6 +6,8 @@ edition = "2024" [dependencies] bitcode.workspace = true quinn.workspace = true +sha2 = "0.11.1" +thiserror = "2.0.21" [lints] workspace = true diff --git a/crates/common/src/certificate.rs b/crates/common/src/certificate.rs new file mode 100644 index 0000000..307cd54 --- /dev/null +++ b/crates/common/src/certificate.rs @@ -0,0 +1,8 @@ +use sha2::{Digest, Sha256}; + +pub fn fingerprint(der: &[u8]) -> String { + Sha256::digest(der) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} diff --git a/crates/common/src/config.rs b/crates/common/src/config.rs index 59795b1..03212b2 100644 --- a/crates/common/src/config.rs +++ b/crates/common/src/config.rs @@ -2,19 +2,34 @@ use std::collections::HashMap; use crate::error::Error; -pub fn parse(content: &str) -> Result, Error> { - content - .lines() - .map(str::trim) - .filter(|line| !line.is_empty() && !line.starts_with('[') && !line.starts_with('#')) - .map(|line| { +pub struct Config(HashMap); + +impl Config { + pub fn parse(content: &str) -> Result { + let mut fields = HashMap::new(); + + for line in content.lines().map(str::trim) { + if line.is_empty() || line.starts_with('[') || line.starts_with('#') { + continue; + } + let (key, value) = line .split_once('=') - .ok_or_else(|| Error::Config(format!("Invalid line: {line}")))?; - Ok(( - key.replace('"', "").trim().to_string(), - value.replace('"', "").trim().to_string(), - )) - }) - .collect() + .ok_or_else(|| Error::Config(format!("invalid line: {line}")))?; + + fields.insert( + key.trim().to_string(), + value.trim().trim_matches('"').to_string(), + ); + } + + Ok(Self(fields)) + } + + pub fn get(&self, key: &str) -> Result { + self.0 + .get(key) + .cloned() + .ok_or_else(|| Error::Config(format!("missing key: {key}"))) + } } diff --git a/crates/common/src/constant.rs b/crates/common/src/constant.rs index 3355380..3d4e2fc 100644 --- a/crates/common/src/constant.rs +++ b/crates/common/src/constant.rs @@ -1,8 +1,9 @@ pub const MAXIMUM_USERNAME_LENGTH: usize = 16; pub const MINIMUM_USERNAME_LENGTH: usize = 3; +pub const MAXIMUM_PASSWORD_LENGTH: usize = 128; +pub const MINIMUM_PASSWORD_LENGTH: usize = 8; pub const MAXIMUM_MESSAGE_LENGTH: usize = 1024; pub const MINIMUM_MESSAGE_LENGTH: usize = 1; pub const MAXIMUM_COMMUNITY_NAME_LENGTH: usize = 16; pub const MINIMUM_COMMUNITY_NAME_LENGTH: usize = 3; pub const MESSAGE_PAGE_LIMIT: usize = 50; -pub const NEWEST_MESSAGE_MARKER: &str = "ZZZZZZZZZZZZZZZZZZZZZZZZZZ"; diff --git a/crates/common/src/error.rs b/crates/common/src/error.rs index 4d3c309..d38dcf1 100644 --- a/crates/common/src/error.rs +++ b/crates/common/src/error.rs @@ -62,39 +62,40 @@ impl Display for InvalidInput { } } -#[derive(Debug, Clone, Encode, Decode)] +#[derive(Debug, Clone, Encode, Decode, thiserror::Error)] pub enum Error { - Authenticate, + #[error("unauthenticated")] + Unauthenticated, + #[error("forbidden")] + Forbidden, + #[error("not found")] + NotFound, + #[error("already taken")] + Taken, + #[error("wrong credentials")] + WrongCredentials, + #[error("server error")] Server, + #[error("channel closed")] ChannelClosed, + #[error("config: {0}")] Config(String), + #[error("network: {0}")] Network(String), + #[error("decode: {0}")] Decode(String), + #[error("read bound exceeded ({actual} > {maximum})")] ReadBoundExceed { actual: usize, maximum: usize }, + #[error("username: {0}")] User(InvalidInput), + #[error("password: {0}")] + Password(InvalidInput), + #[error("community name: {0}")] Community(InvalidInput), + #[error("message: {0}")] Message(InvalidInput), -} - -impl std::error::Error for Error {} - -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::Authenticate => write!(f, "Authenticate"), - Error::Server => write!(f, "Server"), - Error::ChannelClosed => write!(f, "Channel closed"), - Error::Config(message) => write!(f, "Config: {message}"), - Error::Network(message) => write!(f, "Network: {message}"), - Error::Decode(message) => write!(f, "Decode: {message}"), - Error::ReadBoundExceed { actual, maximum } => { - write!(f, "Read bound exceeded ({actual} > {maximum})") - } - Error::User(e) => write!(f, "Username: {e}"), - Error::Community(e) => write!(f, "Community name: {e}"), - Error::Message(e) => write!(f, "Message: {e}"), - } - } + #[error("certificate: {0}")] + Certificate(String), } from_display! { Error { diff --git a/crates/common/src/event.rs b/crates/common/src/event.rs new file mode 100644 index 0000000..324fcd7 --- /dev/null +++ b/crates/common/src/event.rs @@ -0,0 +1,14 @@ +use bitcode::{Decode, Encode}; + +use crate::model::{Community, Message, User}; + +#[derive(Debug, Clone, Encode, Decode)] +pub enum Event { + MessageCreated(Message), + MessageUpdated(Message), + MessageDeleted(Message), + MemberJoined { community_id: String, user: User }, + MemberLeft { community_id: String, user_id: String }, + CommunityUpdated(Community), + CommunityDeleted { community_id: String }, +} diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index c7569ef..ac6b26f 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -1,6 +1,8 @@ +pub mod certificate; pub mod config; pub mod constant; pub mod error; +pub mod event; pub mod model; pub mod network; pub mod request; diff --git a/crates/common/src/model.rs b/crates/common/src/model.rs index 0677994..d1533a0 100644 --- a/crates/common/src/model.rs +++ b/crates/common/src/model.rs @@ -10,6 +10,7 @@ pub struct User { pub struct Community { pub id: String, pub name: String, + pub owner_id: String, } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] diff --git a/crates/common/src/network.rs b/crates/common/src/network.rs index becd478..bc1e4d0 100644 --- a/crates/common/src/network.rs +++ b/crates/common/src/network.rs @@ -3,15 +3,14 @@ use quinn::{RecvStream, SendStream}; use crate::{ constant::{MAXIMUM_MESSAGE_LENGTH, MESSAGE_PAGE_LIMIT}, error::Error, - model::Message, + event::Event, request::Request, response::Response, }; -pub const AUTHENTICATION_MAX_READ_LENGTH: usize = 64; pub const REQUEST_MAX_READ_LENGTH: usize = MAXIMUM_MESSAGE_LENGTH * 2; -pub const MESSAGE_MAX_ENCODED_LENGTH: usize = MAXIMUM_MESSAGE_LENGTH * 2; -pub const RESPONSE_MAX_READ_LENGTH: usize = MESSAGE_MAX_ENCODED_LENGTH * MESSAGE_PAGE_LIMIT; +pub const EVENT_MAX_ENCODED_LENGTH: usize = MAXIMUM_MESSAGE_LENGTH * 2; +pub const RESPONSE_MAX_READ_LENGTH: usize = EVENT_MAX_ENCODED_LENGTH * MESSAGE_PAGE_LIMIT; pub async fn send_response(response: &Response, mut send_stream: SendStream) -> Result<(), Error> { send_stream.write_all(&bitcode::encode(response)).await?; @@ -39,8 +38,8 @@ pub async fn send_request( Ok(bitcode::decode(&bytes)?) } -pub async fn send_message(message: &Message, send_stream: &mut SendStream) -> Result<(), Error> { - let payload = bitcode::encode(message); +pub async fn send_event(event: &Event, send_stream: &mut SendStream) -> Result<(), Error> { + let payload = bitcode::encode(event); send_stream .write_all(&(payload.len() as u32).to_le_bytes()) .await?; @@ -48,15 +47,15 @@ pub async fn send_message(message: &Message, send_stream: &mut SendStream) -> Re Ok(()) } -pub async fn receive_message(receive_stream: &mut RecvStream) -> Result { +pub async fn receive_event(receive_stream: &mut RecvStream) -> Result { let mut length_bytes = [0u8; 4]; receive_stream.read_exact(&mut length_bytes).await?; let length = u32::from_le_bytes(length_bytes) as usize; - if length > MESSAGE_MAX_ENCODED_LENGTH { + if length > EVENT_MAX_ENCODED_LENGTH { return Err(Error::ReadBoundExceed { actual: length, - maximum: MESSAGE_MAX_ENCODED_LENGTH, + maximum: EVENT_MAX_ENCODED_LENGTH, }); } diff --git a/crates/common/src/request.rs b/crates/common/src/request.rs index 4a015aa..ee4e91d 100644 --- a/crates/common/src/request.rs +++ b/crates/common/src/request.rs @@ -2,25 +2,24 @@ use bitcode::{Decode, Encode}; #[derive(Debug, Clone, Encode, Decode)] pub enum Request { - Authentication { token: String }, - Deauthentication { token: String }, - CreateUser { username: String }, + Register { username: String, password: String }, + Login { username: String, password: String }, + Resume { token: String }, + Logout, ReadUser { user_id: String }, - UpdateUser { user_id: String, username: String }, - DeleteUser { user_id: String }, + UpdateUser { username: String }, + DeleteUser, CreateCommunity { name: String }, ReadCommunity { community_id: String }, UpdateCommunity { community_id: String, name: String }, DeleteCommunity { community_id: String }, - CreateMessage { user_id: String, community_id: String, body: String }, - ReadMessage { message_id: String }, + SearchCommunity { name: String }, + JoinCommunity { community_id: String }, + LeaveCommunity { community_id: String }, + Communities, + Members { community_id: String }, + CreateMessage { community_id: String, body: String }, UpdateMessage { message_id: String, body: String }, DeleteMessage { message_id: String }, - ReadMessages { community_id: String, marker: String, limit: usize }, - JoinCommunity { user_id: String, community_id: String }, - LeaveCommunity { user_id: String, community_id: String }, - IsUserIn { user_id: String, community_id: String }, - UsersIn { community_id: String }, - CommunitiesOf { user_id: String }, - SearchCommunity { name: String }, + ReadMessages { community_id: String, before: Option }, } diff --git a/crates/common/src/response.rs b/crates/common/src/response.rs index 627c7d7..56439f6 100644 --- a/crates/common/src/response.rs +++ b/crates/common/src/response.rs @@ -7,26 +7,13 @@ use crate::{ #[derive(Debug, Clone, Encode, Decode)] pub enum Response { - Authentication(User), - Deauthentication(User), - CreateUser(User), - ReadUser(User), - UpdateUser(User), - DeleteUser(User), - CreateCommunity(Community), - ReadCommunity(Community), - UpdateCommunity(Community), - DeleteCommunity(Community), - CreateMessage(Message), - ReadMessage(Message), - UpdateMessage(Message), - DeleteMessage(Message), - ReadMessages(Vec), - JoinCommunity, - LeaveCommunity, - IsUserIn(bool), - UsersIn(Vec), - CommunitiesOf(Vec), - SearchCommunity(Vec), + Session { user: User, token: String }, + User(User), + Community(Community), + Communities(Vec), + Members(Vec), + Message(Message), + Messages(Vec), + Done, Error(Error), } diff --git a/crates/common/src/validate.rs b/crates/common/src/validate.rs index a1c10a0..1968b27 100644 --- a/crates/common/src/validate.rs +++ b/crates/common/src/validate.rs @@ -1,7 +1,8 @@ use crate::{ constant::{ - MAXIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_USERNAME_LENGTH, - MINIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_MESSAGE_LENGTH, MINIMUM_USERNAME_LENGTH, + MAXIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_PASSWORD_LENGTH, + MAXIMUM_USERNAME_LENGTH, MINIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_MESSAGE_LENGTH, + MINIMUM_PASSWORD_LENGTH, MINIMUM_USERNAME_LENGTH, }, error::{Error, InvalidInput}, }; @@ -43,6 +44,16 @@ pub fn validate_username(username: &str) -> Result<(), Error> { .map_err(Error::User) } +pub fn validate_password(password: &str) -> Result<(), Error> { + check( + password, + MINIMUM_PASSWORD_LENGTH, + MAXIMUM_PASSWORD_LENGTH, + false, + ) + .map_err(Error::Password) +} + pub fn validate_community_name(name: &str) -> Result<(), Error> { check( name, diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index c37fab2..4d98e33 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -3,19 +3,20 @@ name = "server" version = "0.1.0" edition = "2024" -[features] -default = ["rcgen"] -rcgen = ["dep:rcgen"] - [dependencies] common.workspace = true -rcgen = { version = "0.14.10", optional = true } +rcgen = "0.14.10" tokio.workspace = true quinn = { workspace = true, features = ["rustls-aws-lc-rs"] } bitcode.workspace = true rustls.workspace = true turso = "0.9.0-pre.6" ulid = "3.0.0" +argon2 = "0.6.0" +getrandom = "0.4.3" +thiserror = "2.0.21" +tracing = "0.1.44" +tracing-subscriber = "0.3.23" [lints] workspace = true diff --git a/crates/server/src/authentication.rs b/crates/server/src/authentication.rs index 5f48b14..380d58e 100644 --- a/crates/server/src/authentication.rs +++ b/crates/server/src/authentication.rs @@ -1,11 +1,128 @@ -use common::{error::Error as CommonError, model::User}; +use argon2::{Argon2, PasswordHasher, PasswordVerifier}; +use common::{ + error::Error as CommonError, + model::User, + validate::{validate_password, validate_username}, +}; +use turso::Connection; -use crate::{database::DB, error::Error, user}; +use crate::{error::Error, user}; -pub async fn authenticate(token: &str, db: &DB) -> Result { - user::read_by_username(token, db) +const SALT_LENGTH: usize = 16; +const TOKEN_LENGTH: usize = 32; + +fn random_bytes() -> Result<[u8; N], Error> { + let mut bytes = [0u8; N]; + getrandom::fill(&mut bytes).map_err(|error| Error::Hash(format!("random: {error}")))?; + + Ok(bytes) +} + +fn hash(password: &str) -> Result { + let salt = random_bytes::()?; + let hash = Argon2::default() + .hash_password_with_salt(password.as_bytes(), &salt) + .map_err(|error| Error::Hash(error.to_string()))?; + + Ok(hash.to_string()) +} + +fn verify(password: &str, password_hash: &str) -> Result<(), Error> { + Argon2::default() + .verify_password(password.as_bytes(), password_hash) + .map_err(|_| Error::from(CommonError::WrongCredentials)) +} + +async fn open_session(user_id: &str, conn: &Connection) -> Result { + let token: String = random_bytes::()? + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + + conn.execute( + "INSERT INTO session (token, user_id) VALUES (?1, ?2)", + (token.as_str(), user_id), + ) + .await?; + + Ok(token) +} + +pub async fn register( + username: &str, + password: &str, + conn: &mut Connection, +) -> Result<(User, String), Error> { + validate_username(username)?; + validate_password(password)?; + + let tx = conn.transaction().await?; + if user::by_username(username, &tx).await?.is_some() { + return Err(CommonError::Taken.into()); + } + let user = user::create(username, &hash(password)?, &tx).await?; + let token = open_session(&user.id, &tx).await?; + tx.commit().await?; + + Ok((user, token)) +} + +pub async fn login( + username: &str, + password: &str, + conn: &Connection, +) -> Result<(User, String), Error> { + let (user, password_hash) = user::credentials(username, conn) .await? - .into_iter() - .next() - .ok_or(Error::Common(CommonError::Authenticate)) + .ok_or(CommonError::WrongCredentials)?; + verify(password, &password_hash)?; + let token = open_session(&user.id, conn).await?; + + Ok((user, token)) +} + +pub async fn resume(token: &str, conn: &Connection) -> Result { + let mut rows = conn + .query( + "SELECT user.id, user.username FROM session JOIN user ON user.id = session.user_id WHERE session.token = ?1", + (token,), + ) + .await?; + let row = rows.next().await?.ok_or(CommonError::WrongCredentials)?; + + user::from_row(&row) +} + +pub async fn logout(token: &str, conn: &Connection) -> Result<(), Error> { + conn.execute("DELETE FROM session WHERE token = ?1", (token,)) + .await?; + + Ok(()) +} + +#[cfg(test)] +mod tests { + use common::error::Error as CommonError; + + use crate::{authentication, database, error::Error, test}; + + #[tokio::test] + async fn register_and_login() { + let db = test::get_database().await; + let mut conn = database::connect(&db).await.unwrap(); + + let (registered_user, _) = authentication::register("Tahinli", "correct horse", &mut conn) + .await + .unwrap(); + let (logged_in_user, _) = authentication::login("Tahinli", "correct horse", &conn) + .await + .unwrap(); + let wrong_password = authentication::login("Tahinli", "wrong password", &conn).await; + + assert_eq!(registered_user, logged_in_user); + assert!(matches!( + wrong_password, + Err(Error::Common(CommonError::WrongCredentials)) + )); + } } diff --git a/crates/server/src/certificate.rs b/crates/server/src/certificate.rs new file mode 100644 index 0000000..3ed6661 --- /dev/null +++ b/crates/server/src/certificate.rs @@ -0,0 +1,42 @@ +use std::{fs, path::Path}; + +use common::certificate::fingerprint; +use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer}; +use tracing::info; + +use crate::error::Error; + +const SUBJECT_ALT_NAME: &str = "localhost"; + +fn certificate_error(error: impl std::fmt::Display) -> Error { + Error::Common(common::error::Error::Certificate(error.to_string())) +} + +fn generate(certificate_path: &str, key_path: &str) -> Result<(Vec, Vec), Error> { + let certified = rcgen::generate_simple_self_signed(vec![SUBJECT_ALT_NAME.to_string()]) + .map_err(certificate_error)?; + let certificate = certified.cert.der().to_vec(); + let key = certified.signing_key.serialize_der(); + + fs::write(certificate_path, &certificate)?; + fs::write(key_path, &key)?; + + Ok((certificate, key)) +} + +pub fn load(certificate_path: &str, key_path: &str) -> Result { + let (certificate, key) = if Path::new(certificate_path).exists() && Path::new(key_path).exists() + { + (fs::read(certificate_path)?, fs::read(key_path)?) + } else { + generate(certificate_path, key_path)? + }; + + info!("certificate fingerprint {}", fingerprint(&certificate)); + + quinn::ServerConfig::with_single_cert( + vec![CertificateDer::from(certificate)], + PrivatePkcs8KeyDer::from(key).into(), + ) + .map_err(certificate_error) +} diff --git a/crates/server/src/community.rs b/crates/server/src/community.rs index 2037517..2a91bc9 100644 --- a/crates/server/src/community.rs +++ b/crates/server/src/community.rs @@ -1,48 +1,46 @@ -use common::{model::Community, validate::validate_community_name}; -use turso::Row; +use common::{error::Error as CommonError, model::Community, validate::validate_community_name}; +use turso::{Connection, Row}; -use crate::{ - database::{DB, new_id}, - error::Error, -}; +use crate::{database::new_id, error::Error}; fn from_row(row: &Row) -> Result { Ok(Community { id: row.get(0)?, name: row.get(1)?, + owner_id: row.get(2)?, }) } -pub async fn create(name: &str, db: &DB) -> Result { +pub async fn create(name: &str, owner_id: &str, conn: &Connection) -> Result { validate_community_name(name)?; - let mut rows = db + let mut rows = conn .query( - "INSERT INTO community (id, name) VALUES (?1, ?2) RETURNING id, name", - (new_id(), name), + "INSERT INTO community (id, name, owner_id) VALUES (?1, ?2, ?3) RETURNING id, name, owner_id", + (new_id(), name, owner_id), ) .await?; - let row = rows.next().await?.ok_or(Error::NotFound)?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; from_row(&row) } -pub async fn read(community_id: &str, db: &DB) -> Result { - let mut rows = db +pub async fn read(community_id: &str, conn: &Connection) -> Result { + let mut rows = conn .query( - "SELECT id, name FROM community WHERE id = ?1", + "SELECT id, name, owner_id FROM community WHERE id = ?1", (community_id,), ) .await?; - let row = rows.next().await?.ok_or(Error::NotFound)?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; from_row(&row) } -pub async fn read_by_name(name: &str, db: &DB) -> Result, Error> { - let mut rows = db +pub async fn read_by_name(name: &str, conn: &Connection) -> Result, Error> { + let mut rows = conn .query( - "SELECT id, name FROM community WHERE name = ?1 ORDER BY id", + "SELECT id, name, owner_id FROM community WHERE name = ?1 ORDER BY id", (name,), ) .await?; @@ -55,51 +53,78 @@ pub async fn read_by_name(name: &str, db: &DB) -> Result, Error> Ok(communities) } -pub async fn update(community_id: &str, name: &str, db: &DB) -> Result { +pub async fn communities_of(user_id: &str, conn: &Connection) -> Result, Error> { + let mut rows = conn + .query( + "SELECT community.id, community.name, community.owner_id FROM community JOIN user_community ON user_community.community_id = community.id WHERE user_community.user_id = ?1 ORDER BY community.id", + (user_id,), + ) + .await?; + + let mut communities = Vec::new(); + while let Some(row) = rows.next().await? { + communities.push(from_row(&row)?); + } + + Ok(communities) +} + +pub async fn update(community_id: &str, name: &str, conn: &Connection) -> Result { validate_community_name(name)?; - let mut rows = db + let mut rows = conn .query( - "UPDATE community SET name = ?2 WHERE id = ?1 RETURNING id, name", + "UPDATE community SET name = ?2 WHERE id = ?1 RETURNING id, name, owner_id", (community_id, name), ) .await?; - let row = rows.next().await?.ok_or(Error::NotFound)?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; from_row(&row) } -pub async fn delete(community_id: &str, db: &DB) -> Result { - let mut rows = db +pub async fn delete(community_id: &str, conn: &Connection) -> Result { + let mut rows = conn .query( - "DELETE FROM community WHERE id = ?1 RETURNING id, name", + "DELETE FROM community WHERE id = ?1 RETURNING id, name, owner_id", (community_id,), ) .await?; - let row = rows.next().await?.ok_or(Error::NotFound)?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; from_row(&row) } #[cfg(test)] mod tests { - use crate::{community, error::Error, test}; + use common::error::Error as CommonError; + + use crate::{community, database, error::Error, test, user}; #[tokio::test] async fn create() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); - let community = community::create("Tahinli", &db).await.unwrap(); + let community = community::create("Tahinli", &owner.id, &conn) + .await + .unwrap(); assert_eq!("Tahinli", community.name); + assert_eq!(owner.id, community.owner_id); } #[tokio::test] async fn read() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); - let created_community = community::create("Tahinli", &db).await.unwrap(); - let searched_community = community::read(&created_community.id, &db).await.unwrap(); + let created_community = community::create("Tahinli", &owner.id, &conn) + .await + .unwrap(); + let searched_community = community::read(&created_community.id, &conn).await.unwrap(); assert_eq!(created_community, searched_community); } @@ -107,12 +132,20 @@ mod tests { #[tokio::test] async fn read_by_name() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); - let community_1 = community::create("Tahinli", &db).await.unwrap(); - let community_2 = community::create("Tahinli", &db).await.unwrap(); - let _community_3 = community::create("Not Tahinli", &db).await.unwrap(); + let community_1 = community::create("Tahinli", &owner.id, &conn) + .await + .unwrap(); + let community_2 = community::create("Tahinli", &owner.id, &conn) + .await + .unwrap(); + let _community_3 = community::create("Not Tahinli", &owner.id, &conn) + .await + .unwrap(); - let searched_communities = community::read_by_name("Tahinli", &db).await.unwrap(); + let searched_communities = community::read_by_name("Tahinli", &conn).await.unwrap(); assert_eq!(vec![community_1, community_2], searched_communities); } @@ -120,12 +153,16 @@ mod tests { #[tokio::test] async fn update() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); - let created_community = community::create("Tahinli", &db).await.unwrap(); - let updated_community = community::update(&created_community.id, "Not Tahinli", &db) + let created_community = community::create("Tahinli", &owner.id, &conn) + .await + .unwrap(); + let updated_community = community::update(&created_community.id, "Not Tahinli", &conn) .await .unwrap(); - let searched_community = community::read(&created_community.id, &db).await.unwrap(); + let searched_community = community::read(&created_community.id, &conn).await.unwrap(); assert_eq!(created_community.id, searched_community.id); assert_eq!(updated_community, searched_community); @@ -135,18 +172,28 @@ mod tests { #[tokio::test] async fn update_on_missing_community() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); - let updated_community = community::update("missing", "Not Tahinli", &db).await; + let updated_community = community::update("missing", "Not Tahinli", &conn).await; - assert!(matches!(updated_community, Err(Error::NotFound))); + assert!(matches!( + updated_community, + Err(Error::Common(CommonError::NotFound)) + )); } #[tokio::test] async fn delete() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); - let created_community = community::create("Tahinli", &db).await.unwrap(); - let deleted_community = community::delete(&created_community.id, &db).await.unwrap(); + let created_community = community::create("Tahinli", &owner.id, &conn) + .await + .unwrap(); + let deleted_community = community::delete(&created_community.id, &conn) + .await + .unwrap(); assert_eq!(created_community, deleted_community); } diff --git a/crates/server/src/database.rs b/crates/server/src/database.rs index 339761c..da16401 100644 --- a/crates/server/src/database.rs +++ b/crates/server/src/database.rs @@ -1,52 +1,93 @@ -use std::sync::{LazyLock, Mutex}; +use std::{ + sync::{LazyLock, Mutex}, + time::Duration, +}; +use turso::Connection; use ulid::Generator; use crate::error::Error; -pub type DB = turso::Connection; +pub type DB = turso::Database; static ULID: LazyLock> = LazyLock::new(|| Mutex::new(Generator::new())); -pub async fn connect(path: &str) -> Result { - let database = turso::Builder::new_local(path).build().await?; +const BUSY_TIMEOUT: Duration = Duration::from_secs(5); - Ok(database.connect()?) +const MIGRATIONS: &[&str] = &[" + CREATE TABLE user ( + id TEXT PRIMARY KEY, + username TEXT NOT NULL UNIQUE, + password_hash TEXT NOT NULL + ); + + CREATE TABLE session ( + token TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE + ); + + CREATE TABLE community ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + owner_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE + ); + + CREATE TABLE message ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, + community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, + body TEXT NOT NULL + ); + + CREATE INDEX message_community_id_id ON message (community_id, id); + + CREATE TABLE user_community ( + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, + community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, + PRIMARY KEY (user_id, community_id) + ); +"]; + +pub async fn open(path: &str) -> Result { + let db = turso::Builder::new_local(path).build().await?; + migrate(&db).await?; + + Ok(db) } -pub async fn migrate(db: &DB) -> Result<(), Error> { - db.execute_batch( - " - CREATE TABLE IF NOT EXISTS user ( - id TEXT PRIMARY KEY, - username TEXT NOT NULL - ); - - CREATE TABLE IF NOT EXISTS community ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL - ); - - CREATE TABLE IF NOT EXISTS message ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL, - community_id TEXT NOT NULL, - body TEXT NOT NULL - ); - CREATE INDEX IF NOT EXISTS message_community_id ON message (community_id); - - CREATE TABLE IF NOT EXISTS user_community ( - user_id TEXT NOT NULL, - community_id TEXT NOT NULL, - PRIMARY KEY (user_id, community_id) - ); - ", - ) - .await?; +pub async fn connect(db: &DB) -> Result { + let conn = db.connect()?; + conn.busy_timeout(BUSY_TIMEOUT)?; + conn.execute_batch("PRAGMA foreign_keys = ON;").await?; + + Ok(conn) +} + +async fn migrate(db: &DB) -> Result<(), Error> { + let mut conn = connect(db).await?; + let applied = user_version(&conn).await?; + + for (index, migration) in MIGRATIONS.iter().enumerate().skip(applied) { + let tx = conn.transaction().await?; + tx.execute_batch(migration).await?; + tx.pragma_update("user_version", index + 1).await?; + tx.commit().await?; + } Ok(()) } +async fn user_version(conn: &Connection) -> Result { + let mut rows = conn.query("PRAGMA user_version", ()).await?; + let row = rows + .next() + .await? + .ok_or(turso::Error::QueryReturnedNoRows)?; + let version: i64 = row.get(0)?; + + Ok(version as usize) +} + pub fn new_id() -> String { loop { match ULID.lock().unwrap().generate() { diff --git a/crates/server/src/error.rs b/crates/server/src/error.rs index 06db31a..75397d6 100644 --- a/crates/server/src/error.rs +++ b/crates/server/src/error.rs @@ -1,24 +1,14 @@ -use std::fmt::Display; - use common::error_from; +use tracing::error; -#[derive(Debug)] +#[derive(Debug, thiserror::Error)] pub enum Error { - Common(common::error::Error), - Database(turso::Error), - NotFound, -} - -impl std::error::Error for Error {} - -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::Common(error) => write!(f, "{error}"), - Error::Database(error) => write!(f, "Database: {error}"), - Error::NotFound => write!(f, "Not found"), - } - } + #[error(transparent)] + Common(#[from] common::error::Error), + #[error(transparent)] + Database(#[from] turso::Error), + #[error("password hash: {0}")] + Hash(String), } impl From for common::error::Error { @@ -26,7 +16,7 @@ impl From for common::error::Error { match value { Error::Common(error) => error, error => { - eprintln!("Error: {error}"); + error!("{error}"); common::error::Error::Server } @@ -35,9 +25,6 @@ impl From for common::error::Error { } error_from! { Error { - common::error::Error => Error::Common, - turso::Error => Error::Database, - std::net::AddrParseError => Error::Common as common::error::Error, std::io::Error => Error::Common as common::error::Error, quinn::ConnectionError => Error::Common as common::error::Error, diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index 3e0f5c3..9cf74cc 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -1,4 +1,5 @@ pub mod authentication; +pub mod certificate; pub mod community; pub mod database; pub mod error; @@ -11,6 +12,10 @@ pub mod user_community; #[cfg(test)] mod test; +use common::config::Config; + +use crate::error::Error; + const SERVER_CONFIG_FILE_PATH: &str = concat!( env!("CARGO_MANIFEST_DIR"), "/../../configs/server_config.toml" @@ -19,32 +24,31 @@ const SERVER_CONFIG_FILE_PATH: &str = concat!( pub struct ServerConfig { pub database_path: String, pub server_address: String, + pub certificate_path: String, + pub key_path: String, } -impl Default for ServerConfig { - fn default() -> Self { - let content = std::fs::read_to_string(SERVER_CONFIG_FILE_PATH).unwrap(); - let mut fields = common::config::parse(&content).unwrap(); +impl ServerConfig { + fn parse(content: &str) -> Result { + let config = Config::parse(content)?; - Self { - database_path: fields.remove("database_path").unwrap(), - server_address: fields.remove("server_address").unwrap(), - } + Ok(Self { + database_path: config.get("database_path")?, + server_address: config.get("server_address")?, + certificate_path: config.get("certificate_path")?, + key_path: config.get("key_path")?, + }) } } -pub async fn showtime() { - rustls::crypto::aws_lc_rs::default_provider() - .install_default() - .unwrap(); - let server_config = ServerConfig::default(); +pub async fn showtime() -> Result<(), Error> { + let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + + let content = std::fs::read_to_string(SERVER_CONFIG_FILE_PATH)?; + let config = ServerConfig::parse(&content)?; - let database = database::connect(&server_config.database_path) - .await - .unwrap(); - database::migrate(&database).await.unwrap(); + let database = database::open(&config.database_path).await?; + let certificate = certificate::load(&config.certificate_path, &config.key_path)?; - network::serve(&server_config.server_address, &database) - .await - .unwrap(); + network::serve(&config.server_address, certificate, database).await } diff --git a/crates/server/src/main.rs b/crates/server/src/main.rs index 44a1a95..fde3fa7 100644 --- a/crates/server/src/main.rs +++ b/crates/server/src/main.rs @@ -1,6 +1,8 @@ use server::showtime; #[tokio::main] -async fn main() { - showtime().await; +async fn main() -> Result<(), server::error::Error> { + tracing_subscriber::fmt().with_max_level(tracing::Level::INFO).init(); + + showtime().await } diff --git a/crates/server/src/message.rs b/crates/server/src/message.rs index b5e3f81..8f0d8b5 100644 --- a/crates/server/src/message.rs +++ b/crates/server/src/message.rs @@ -1,10 +1,10 @@ -use common::{model::Message, validate::validate_message_body}; -use turso::Row; - -use crate::{ - database::{DB, new_id}, - error::Error, +use common::{ + constant::MESSAGE_PAGE_LIMIT, error::Error as CommonError, model::Message, + validate::validate_message_body, }; +use turso::{Connection, Row}; + +use crate::{database::new_id, error::Error}; fn from_row(row: &Row) -> Result { Ok(Message { @@ -19,43 +19,42 @@ pub async fn create( user_id: &str, community_id: &str, body: &str, - db: &DB, + conn: &Connection, ) -> Result { validate_message_body(body)?; - let mut rows = db + let mut rows = conn .query( "INSERT INTO message (id, user_id, community_id, body) VALUES (?1, ?2, ?3, ?4) RETURNING id, user_id, community_id, body", (new_id(), user_id, community_id, body), ) .await?; - let row = rows.next().await?.ok_or(Error::NotFound)?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; from_row(&row) } -pub async fn read(message_id: &str, db: &DB) -> Result { - let mut rows = db +pub async fn read(message_id: &str, conn: &Connection) -> Result { + let mut rows = conn .query( "SELECT id, user_id, community_id, body FROM message WHERE id = ?1", (message_id,), ) .await?; - let row = rows.next().await?.ok_or(Error::NotFound)?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; from_row(&row) } pub async fn read_page( community_id: &str, - marker: &str, - limit: usize, - db: &DB, + before: Option<&str>, + conn: &Connection, ) -> Result, Error> { - let mut rows = db + let mut rows = conn .query( - "SELECT id, user_id, community_id, body FROM message WHERE community_id = ?1 AND id <= ?2 ORDER BY id DESC LIMIT ?3", - (community_id, marker, limit as i64), + "SELECT id, user_id, community_id, body FROM message WHERE community_id = ?1 AND (?2 IS NULL OR id < ?2) ORDER BY id DESC LIMIT ?3", + (community_id, before, MESSAGE_PAGE_LIMIT as i64), ) .await?; @@ -68,43 +67,46 @@ pub async fn read_page( Ok(messages) } -pub async fn update(message_id: &str, body: &str, db: &DB) -> Result { +pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result { validate_message_body(body)?; - let mut rows = db + let mut rows = conn .query( "UPDATE message SET body = ?2 WHERE id = ?1 RETURNING id, user_id, community_id, body", (message_id, body), ) .await?; - let row = rows.next().await?.ok_or(Error::NotFound)?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; from_row(&row) } -pub async fn delete(message_id: &str, db: &DB) -> Result { - let mut rows = db +pub async fn delete(message_id: &str, conn: &Connection) -> Result { + let mut rows = conn .query( "DELETE FROM message WHERE id = ?1 RETURNING id, user_id, community_id, body", (message_id,), ) .await?; - let row = rows.next().await?.ok_or(Error::NotFound)?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; from_row(&row) } #[cfg(test)] mod tests { - use crate::{community, error::Error, message, test, user}; + use common::error::Error as CommonError; + + use crate::{community, database, error::Error, message, test, user}; #[tokio::test] async fn create() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); + let user = user::create("Tahinli", "hash", &conn).await.unwrap(); + let community = community::create("Tahinli", &user.id, &conn).await.unwrap(); - let user = user::create("Tahinli", &db).await.unwrap(); - let community = community::create("Tahinli", &db).await.unwrap(); - let message = message::create(&user.id, &community.id, "Tahinli", &db) + let message = message::create(&user.id, &community.id, "Tahinli", &conn) .await .unwrap(); @@ -116,14 +118,14 @@ mod tests { #[tokio::test] async fn read() { let db = test::get_database().await; - - let user = user::create("Tahinli", &db).await.unwrap(); - let community = community::create("Tahinli", &db).await.unwrap(); - let created_message = message::create(&user.id, &community.id, "Tahinli", &db) + let conn = database::connect(&db).await.unwrap(); + let user = user::create("Tahinli", "hash", &conn).await.unwrap(); + let community = community::create("Tahinli", &user.id, &conn).await.unwrap(); + let created_message = message::create(&user.id, &community.id, "Tahinli", &conn) .await .unwrap(); - let searched_message = message::read(&created_message.id, &db).await.unwrap(); + let searched_message = message::read(&created_message.id, &conn).await.unwrap(); assert_eq!(created_message, searched_message); } @@ -131,51 +133,51 @@ mod tests { #[tokio::test] async fn read_page() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); + let user_1 = user::create("Tahinli", "hash", &conn).await.unwrap(); + let user_2 = user::create("Not Tahinli", "hash", &conn).await.unwrap(); + let community = community::create("Tahinli", &user_1.id, &conn) + .await + .unwrap(); - let user_1 = user::create("Tahinli", &db).await.unwrap(); - let user_2 = user::create("Not Tahinli", &db).await.unwrap(); - let community = community::create("Tahinli", &db).await.unwrap(); - - let message_1 = message::create(&user_1.id, &community.id, "Tahinli", &db) + let message_1 = message::create(&user_1.id, &community.id, "Tahinli", &conn) .await .unwrap(); - let message_2 = message::create(&user_2.id, &community.id, "Tahinli", &db) + let message_2 = message::create(&user_2.id, &community.id, "Tahinli", &conn) .await .unwrap(); - let message_3 = message::create(&user_2.id, &community.id, "Tahinli", &db) + let message_3 = message::create(&user_2.id, &community.id, "Tahinli", &conn) .await .unwrap(); - let searched_messages = message::read_page(&community.id, &message_3.id, 3, &db) + let newest = message::read_page(&community.id, None, &conn) .await .unwrap(); - - assert_eq!( - vec![message_1, message_2, message_3.clone()], - searched_messages - ); - - let searched_messages = message::read_page(&community.id, &message_3.id, 1, &db) + let older = message::read_page(&community.id, Some(&message_3.id), &conn) .await .unwrap(); - assert_eq!(vec![message_3], searched_messages); + assert_eq!( + vec![message_1.clone(), message_2.clone(), message_3], + newest + ); + assert_eq!(vec![message_1, message_2], older); } #[tokio::test] async fn update() { let db = test::get_database().await; - - let user = user::create("Tahinli", &db).await.unwrap(); - let community = community::create("Tahinli", &db).await.unwrap(); - let created_message = message::create(&user.id, &community.id, "Tahinli", &db) + let conn = database::connect(&db).await.unwrap(); + let user = user::create("Tahinli", "hash", &conn).await.unwrap(); + let community = community::create("Tahinli", &user.id, &conn).await.unwrap(); + let created_message = message::create(&user.id, &community.id, "Tahinli", &conn) .await .unwrap(); - let updated_message = message::update(&created_message.id, "Not Tahinli", &db) + let updated_message = message::update(&created_message.id, "Not Tahinli", &conn) .await .unwrap(); - let searched_message = message::read(&created_message.id, &db).await.unwrap(); + let searched_message = message::read(&created_message.id, &conn).await.unwrap(); assert_eq!(created_message.user_id, updated_message.user_id); assert_eq!(created_message.community_id, updated_message.community_id); @@ -186,23 +188,27 @@ mod tests { #[tokio::test] async fn update_on_missing_message() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); - let updated_message = message::update("missing", "Tahinli", &db).await; + let updated_message = message::update("missing", "Tahinli", &conn).await; - assert!(matches!(updated_message, Err(Error::NotFound))); + assert!(matches!( + updated_message, + Err(Error::Common(CommonError::NotFound)) + )); } #[tokio::test] async fn delete() { let db = test::get_database().await; - - let user = user::create("Tahinli", &db).await.unwrap(); - let community = community::create("Tahinli", &db).await.unwrap(); - let created_message = message::create(&user.id, &community.id, "Tahinli", &db) + let conn = database::connect(&db).await.unwrap(); + let user = user::create("Tahinli", "hash", &conn).await.unwrap(); + let community = community::create("Tahinli", &user.id, &conn).await.unwrap(); + let created_message = message::create(&user.id, &community.id, "Tahinli", &conn) .await .unwrap(); - let deleted_message = message::delete(&created_message.id, &db).await.unwrap(); + let deleted_message = message::delete(&created_message.id, &conn).await.unwrap(); assert_eq!(created_message, deleted_message); } diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index c2fba0f..3af6191 100644 --- a/crates/server/src/network.rs +++ b/crates/server/src/network.rs @@ -1,40 +1,63 @@ -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use common::{ - model::Message, - network::{ - AUTHENTICATION_MAX_READ_LENGTH, REQUEST_MAX_READ_LENGTH, receive_request, send_message, - send_response, - }, - request::Request, - response::Response, + event::Event as Push, + model::User, + network::{REQUEST_MAX_READ_LENGTH, receive_request, send_event, send_response}, }; use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream}; use tokio::{sync::mpsc, task::JoinHandle}; +use tracing::{info, warn}; use crate::{ - authentication::authenticate, database::DB, error::Error, request::handle_request, - user_community, + database::DB, + error::Error, + request::{self, Broadcast}, }; const CHANNEL_LENGTH: usize = 2048; const SESSION_LENGTH: usize = 64; -#[cfg(feature = "rcgen")] -fn config() -> quinn::ServerConfig { - use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer}; +#[derive(Clone)] +pub enum State { + Anonymous, + Authenticated { user: User, token: String }, +} - let certificate = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); - let certificate_der = CertificateDer::from(certificate.cert); - let certificate_key = PrivatePkcs8KeyDer::from(certificate.signing_key.serialize_der()); - quinn::ServerConfig::with_single_cert(vec![certificate_der], certificate_key.into()).unwrap() +enum Event { + Connected { + connection_id: usize, + connection: Connection, + send_stream: SendStream, + }, + SignedIn { + connection_id: usize, + user_id: String, + }, + SignedOut { + connection_id: usize, + }, + Broadcast(Broadcast), } -pub async fn serve(server_address: &str, db: &DB) -> Result<(), Error> { - let endpoint = Endpoint::server(config(), server_address.parse()?)?; +struct Session { + connection_id: usize, + user_id: Option, + connection: Connection, + event_sender: mpsc::Sender>, + writer: JoinHandle<()>, +} + +pub async fn serve( + server_address: &str, + server_config: quinn::ServerConfig, + db: DB, +) -> Result<(), Error> { + let endpoint = Endpoint::server(server_config, server_address.parse()?)?; + info!("listening on {server_address}"); let (event_sender, event_receiver) = mpsc::channel(CHANNEL_LENGTH); - tokio::spawn(the_actor(event_receiver, db.clone())); + tokio::spawn(the_actor(event_receiver)); while let Some(incoming) = endpoint.accept().await { tokio::spawn(handle_connection( @@ -48,83 +71,69 @@ pub async fn serve(server_address: &str, db: &DB) -> Result<(), Error> { } async fn handle_connection(incoming: Incoming, event_sender: mpsc::Sender, db: DB) { - match incoming.await { - Ok(connection) => { - if let Err(error) = establish_connection(&connection, event_sender, &db).await { - eprintln!("Error = Endpoint Accept | {error}"); - connection.close(0u8.into(), b"kendine iyi bak"); - } - } - Err(error) => eprintln!("Error = Connection | {error}"), + if let Err(error) = serve_connection(incoming, event_sender, db).await { + warn!("connection: {error}"); } } -async fn establish_connection( - connection: &Connection, +async fn serve_connection( + incoming: Incoming, event_sender: mpsc::Sender, - db: &DB, + db: DB, ) -> Result<(), Error> { - let (send_stream, receive_stream) = connection.accept_bi().await?; - - let first_request = receive_request(receive_stream, AUTHENTICATION_MAX_READ_LENGTH).await?; - - if let Request::Authentication { token } = first_request { - let user = authenticate(&token, db).await?; - let response = Response::Authentication(user.clone()); - - tokio::spawn(listen( - user.id.clone(), - connection.clone(), - event_sender.clone(), - db.clone(), - )); - - send_response(&response, send_stream).await?; - - let send_stream = connection.open_uni().await?; - let _ = event_sender - .send(Event::Joined { - user_id: user.id, - send_stream, - connection: connection.clone(), - }) - .await; + let connection = incoming.await?; + let send_stream = connection.open_uni().await?; + let _ = event_sender + .send(Event::Connected { + connection_id: connection.stable_id(), + connection: connection.clone(), + send_stream, + }) + .await; - Ok(()) - } else { - Err(Error::Common(common::error::Error::Authenticate)) - } -} + let state = Arc::new(Mutex::new(State::Anonymous)); -async fn listen( - user_id: String, - connection: Connection, - event_sender: mpsc::Sender, - db: DB, -) { while let Ok((send_stream, receive_stream)) = connection.accept_bi().await { - tokio::spawn(read_and_answer( - user_id.clone(), + tokio::spawn(answer( + connection.stable_id(), + Arc::clone(&state), send_stream, receive_stream, event_sender.clone(), db.clone(), )); } + + Ok(()) } -async fn read_and_answer( - user_id: String, +async fn answer( + connection_id: usize, + state: Arc>, send_stream: SendStream, receive_stream: RecvStream, event_sender: mpsc::Sender, db: DB, ) -> Result<(), Error> { let request = receive_request(receive_stream, REQUEST_MAX_READ_LENGTH).await?; - let response = handle_request(&user_id, request, &db).await; - if let Response::CreateMessage(message) = &response { - let _ = event_sender.send(Event::Sent(message.clone())).await; + let before = signed_user_id(&state); + let (response, broadcast) = request::handle(request, &state, &db).await; + let after = signed_user_id(&state); + + if before != after { + let event = match after { + Some(user_id) => Event::SignedIn { + connection_id, + user_id, + }, + None => Event::SignedOut { connection_id }, + }; + let _ = event_sender.send(event).await; + } + + if let Some(broadcast) = broadcast { + let _ = event_sender.send(Event::Broadcast(broadcast)).await; } send_response(&response, send_stream).await?; @@ -132,35 +141,23 @@ async fn read_and_answer( Ok(()) } -enum Event { - Joined { - user_id: String, - send_stream: SendStream, - connection: Connection, - }, - Sent(Message), -} - -struct Session { - pub user_id: String, - pub connection: Connection, - pub message_sender: mpsc::Sender>, - pub writer: JoinHandle<()>, +fn signed_user_id(state: &Mutex) -> Option { + match &*state.lock().unwrap() { + State::Anonymous => None, + State::Authenticated { user, .. } => Some(user.id.clone()), + } } -async fn write_session( - mut message_receiver: mpsc::Receiver>, - mut send_stream: SendStream, -) { - while let Some(message) = message_receiver.recv().await { - if let Err(error) = send_message(&message, &mut send_stream).await { - eprintln!("Error = Message | Session Write | {error}"); +async fn write_session(mut event_receiver: mpsc::Receiver>, mut send_stream: SendStream) { + while let Some(event) = event_receiver.recv().await { + if let Err(error) = send_event(&event, &mut send_stream).await { + warn!("session write: {error}"); break; } } } -async fn the_actor(mut event_receiver: mpsc::Receiver, db: DB) { +async fn the_actor(mut event_receiver: mpsc::Receiver) { let mut sessions: Vec = Vec::new(); while let Some(event) = event_receiver.recv().await { @@ -169,44 +166,56 @@ async fn the_actor(mut event_receiver: mpsc::Receiver, db: DB) { }); match event { - Event::Joined { - user_id, - send_stream, + Event::Connected { + connection_id, connection, + send_stream, } => { - let (message_sender, message_receiver) = mpsc::channel(SESSION_LENGTH); - let writer = tokio::spawn(write_session(message_receiver, send_stream)); + let (event_sender, event_receiver) = mpsc::channel(SESSION_LENGTH); + let writer = tokio::spawn(write_session(event_receiver, send_stream)); sessions.push(Session { - user_id, + connection_id, + user_id: None, connection, - message_sender, + event_sender, writer, }); } - Event::Sent(message) => { - let Ok(users) = user_community::users_in(&message.community_id, &db).await else { - eprintln!( - "Error = Message | Community Member Read | {}", - message.community_id - ); - continue; - }; - - let message = Arc::new(message); + Event::SignedIn { + connection_id, + user_id, + } => { + if let Some(session) = sessions + .iter_mut() + .find(|session| session.connection_id == connection_id) + { + session.user_id = Some(user_id); + } + } + Event::SignedOut { connection_id } => { + if let Some(session) = sessions + .iter_mut() + .find(|session| session.connection_id == connection_id) + { + session.user_id = None; + } + } + Event::Broadcast(broadcast) => { + let event = Arc::new(broadcast.event); sessions.retain(|session| { - if !users.contains(&session.user_id) { + let Some(user_id) = &session.user_id else { + return true; + }; + if !broadcast.user_ids.contains(user_id) { return true; } - match session.message_sender.try_send(Arc::clone(&message)) { + match session.event_sender.try_send(Arc::clone(&event)) { Ok(()) => true, Err(mpsc::error::TrySendError::Full(_)) => { - eprintln!( - "Error = Message | Session Buffer is Full | {}", - session.user_id - ); + warn!("session buffer is full {user_id}"); session.writer.abort(); false } diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index da32c33..e0abe50 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -1,110 +1,354 @@ -use common::{request::Request, response::Response}; +use std::sync::Mutex; + +use common::{ + error::Error as CommonError, + event::Event, + model::{Community, Message, User}, + request::Request, + response::Response, +}; use crate::{ - authentication::authenticate, community, database::DB, error::Error, message, user, - user_community, + authentication, community, + database::{self, DB}, + error::Error, + message, + network::State, + user, user_community, }; -pub async fn handle_request(session_user_id: &str, request: Request, db: &DB) -> Response { - match handle(session_user_id, request, db).await { - Ok(response) => response, - Err(error) => Response::Error(error.into()), +pub struct Broadcast { + pub event: Event, + pub user_ids: Vec, +} + +type Outcome = (Response, Option); + +pub async fn handle(request: Request, state: &Mutex, db: &DB) -> Outcome { + match dispatch(request, state, db).await { + Ok(outcome) => outcome, + Err(error) => (Response::Error(error.into()), None), } } -async fn handle(session_user_id: &str, request: Request, db: &DB) -> Result { - let response = match request { - Request::Authentication { token } => { - Response::Authentication(authenticate(&token, db).await?) +async fn dispatch(request: Request, state: &Mutex, db: &DB) -> Result { + let mut conn = database::connect(db).await?; + + let outcome = match request { + Request::Register { username, password } => { + let (user, token) = authentication::register(&username, &password, &mut conn).await?; + sign_in(state, user, token) + } + Request::Login { username, password } => { + let (user, token) = authentication::login(&username, &password, &conn).await?; + sign_in(state, user, token) + } + Request::Resume { token } => { + let user = authentication::resume(&token, &conn).await?; + sign_in(state, user, token) + } + Request::Logout => { + let (_, token) = authenticated(state)?; + authentication::logout(&token, &conn).await?; + set_state(state, State::Anonymous); + (Response::Done, None) } - Request::Deauthentication { token } => { - Response::Deauthentication(authenticate(&token, db).await?) + Request::ReadUser { user_id } => { + authenticated(state)?; + (Response::User(user::read(&user_id, &conn).await?), None) } - Request::CreateUser { username } => { - Response::CreateUser(user::create(&username, db).await?) + Request::UpdateUser { username } => { + let (me, token) = authenticated(state)?; + let user = user::update(&me.id, &username, &conn).await?; + set_state( + state, + State::Authenticated { + user: user.clone(), + token, + }, + ); + (Response::User(user), None) } - Request::ReadUser { user_id } => Response::ReadUser(user::read(&user_id, db).await?), - Request::UpdateUser { user_id, username } => { - Response::UpdateUser(user::update(&user_id, &username, db).await?) + Request::DeleteUser => { + let (me, _) = authenticated(state)?; + let user = user::delete(&me.id, &conn).await?; + set_state(state, State::Anonymous); + (Response::User(user), None) } - Request::DeleteUser { user_id } => Response::DeleteUser(user::delete(&user_id, db).await?), Request::CreateCommunity { name } => { - let community = community::create(&name, db).await?; - user_community::join(session_user_id, &community.id, db).await?; - Response::CreateCommunity(community) + let (me, _) = authenticated(state)?; + let tx = conn.transaction().await?; + let community = community::create(&name, &me.id, &tx).await?; + user_community::join(&me.id, &community.id, &tx).await?; + tx.commit().await?; + (Response::Community(community), None) } Request::ReadCommunity { community_id } => { - Response::ReadCommunity(community::read(&community_id, db).await?) + authenticated(state)?; + ( + Response::Community(community::read(&community_id, &conn).await?), + None, + ) } Request::UpdateCommunity { community_id, name } => { - Response::UpdateCommunity(community::update(&community_id, &name, db).await?) + let (me, _) = authenticated(state)?; + let existing = community::read(&community_id, &conn).await?; + ensure_owner(&existing, &me)?; + let updated = community::update(&community_id, &name, &conn).await?; + let members = user_community::members(&community_id, &conn).await?; + let event = Event::CommunityUpdated(updated.clone()); + (Response::Community(updated), broadcast(event, &members)) } Request::DeleteCommunity { community_id } => { - Response::DeleteCommunity(community::delete(&community_id, db).await?) + let (me, _) = authenticated(state)?; + let existing = community::read(&community_id, &conn).await?; + ensure_owner(&existing, &me)?; + let tx = conn.transaction().await?; + let members = user_community::members(&community_id, &tx).await?; + let deleted = community::delete(&community_id, &tx).await?; + tx.commit().await?; + let event = Event::CommunityDeleted { + community_id: deleted.id.clone(), + }; + (Response::Community(deleted), broadcast(event, &members)) } - Request::CreateMessage { - user_id, - community_id, - body, - } => { - user::read(&user_id, db).await?; - community::read(&community_id, db).await?; - Response::CreateMessage(message::create(&user_id, &community_id, &body, db).await?) + Request::SearchCommunity { name } => { + authenticated(state)?; + ( + Response::Communities(community::read_by_name(&name, &conn).await?), + None, + ) + } + Request::JoinCommunity { community_id } => { + let (me, _) = authenticated(state)?; + let existing = community::read(&community_id, &conn).await?; + let tx = conn.transaction().await?; + if user_community::is_member(&me.id, &community_id, &tx).await? { + return Err(CommonError::Taken.into()); + } + user_community::join(&me.id, &community_id, &tx).await?; + let members = user_community::members(&community_id, &tx).await?; + tx.commit().await?; + let event = Event::MemberJoined { + community_id, + user: me, + }; + (Response::Community(existing), broadcast(event, &members)) + } + Request::LeaveCommunity { community_id } => { + let (me, _) = authenticated(state)?; + let tx = conn.transaction().await?; + user_community::leave(&me.id, &community_id, &tx).await?; + let members = user_community::members(&community_id, &tx).await?; + if members.is_empty() { + community::delete(&community_id, &tx).await?; + } + tx.commit().await?; + let event = Event::MemberLeft { + community_id, + user_id: me.id, + }; + (Response::Done, broadcast(event, &members)) + } + Request::Communities => { + let (me, _) = authenticated(state)?; + ( + Response::Communities(community::communities_of(&me.id, &conn).await?), + None, + ) } - Request::ReadMessage { message_id } => { - Response::ReadMessage(message::read(&message_id, db).await?) + Request::Members { community_id } => { + let (me, _) = authenticated(state)?; + user_community::ensure_member(&me.id, &community_id, &conn).await?; + ( + Response::Members(user_community::members(&community_id, &conn).await?), + None, + ) + } + Request::CreateMessage { community_id, body } => { + let (me, _) = authenticated(state)?; + user_community::ensure_member(&me.id, &community_id, &conn).await?; + let created = message::create(&me.id, &community_id, &body, &conn).await?; + let members = user_community::members(&community_id, &conn).await?; + let event = Event::MessageCreated(created.clone()); + (Response::Message(created), broadcast(event, &members)) } Request::UpdateMessage { message_id, body } => { - Response::UpdateMessage(message::update(&message_id, &body, db).await?) + let (me, _) = authenticated(state)?; + let existing = message::read(&message_id, &conn).await?; + ensure_author(&existing, &me)?; + let updated = message::update(&message_id, &body, &conn).await?; + let members = user_community::members(&updated.community_id, &conn).await?; + let event = Event::MessageUpdated(updated.clone()); + (Response::Message(updated), broadcast(event, &members)) } Request::DeleteMessage { message_id } => { - Response::DeleteMessage(message::delete(&message_id, db).await?) + let (me, _) = authenticated(state)?; + let existing = message::read(&message_id, &conn).await?; + ensure_author(&existing, &me)?; + let deleted = message::delete(&message_id, &conn).await?; + let members = user_community::members(&deleted.community_id, &conn).await?; + let event = Event::MessageDeleted(deleted.clone()); + (Response::Message(deleted), broadcast(event, &members)) } Request::ReadMessages { community_id, - marker, - limit, - } => Response::ReadMessages(message::read_page(&community_id, &marker, limit, db).await?), - Request::JoinCommunity { - user_id, - community_id, - } => { - user_community::join(&user_id, &community_id, db).await?; - Response::JoinCommunity - } - Request::LeaveCommunity { - user_id, - community_id, - } => { - user_community::leave(&user_id, &community_id, db).await?; - if user_community::users_in(&community_id, db) - .await? - .is_empty() - { - community::delete(&community_id, db).await?; - } - Response::LeaveCommunity - } - Request::IsUserIn { - user_id, - community_id, + before, } => { - user::read(&user_id, db).await?; - community::read(&community_id, db).await?; - Response::IsUserIn(user_community::is_user_in(&user_id, &community_id, db).await?) - } - Request::UsersIn { community_id } => { - community::read(&community_id, db).await?; - Response::UsersIn(user_community::users_in(&community_id, db).await?) - } - Request::CommunitiesOf { user_id } => { - user::read(&user_id, db).await?; - Response::CommunitiesOf(user_community::communities_of(&user_id, db).await?) - } - Request::SearchCommunity { name } => { - Response::SearchCommunity(community::read_by_name(&name, db).await?) + let (me, _) = authenticated(state)?; + user_community::ensure_member(&me.id, &community_id, &conn).await?; + let messages = message::read_page(&community_id, before.as_deref(), &conn).await?; + (Response::Messages(messages), None) } }; - Ok(response) + Ok(outcome) +} + +fn sign_in(state: &Mutex, user: User, token: String) -> Outcome { + set_state( + state, + State::Authenticated { + user: user.clone(), + token: token.clone(), + }, + ); + + (Response::Session { user, token }, None) +} + +fn set_state(state: &Mutex, new_state: State) { + *state.lock().unwrap() = new_state; +} + +fn authenticated(state: &Mutex) -> Result<(User, String), Error> { + match state.lock().unwrap().clone() { + State::Anonymous => Err(CommonError::Unauthenticated.into()), + State::Authenticated { user, token } => Ok((user, token)), + } +} + +fn ensure_owner(community: &Community, me: &User) -> Result<(), Error> { + if community.owner_id != me.id { + return Err(CommonError::Forbidden.into()); + } + + Ok(()) +} + +fn ensure_author(message: &Message, me: &User) -> Result<(), Error> { + if message.user_id != me.id { + return Err(CommonError::Forbidden.into()); + } + + Ok(()) +} + +fn broadcast(event: Event, members: &[User]) -> Option { + Some(Broadcast { + event, + user_ids: members.iter().map(|user| user.id.clone()).collect(), + }) +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use common::{error::Error as CommonError, request::Request, response::Response}; + + use crate::{ + database::{self, DB}, + message, + network::State, + request::handle, + test, + }; + + async fn signed_in(username: &str, db: &DB) -> Mutex { + let state = Mutex::new(State::Anonymous); + handle( + Request::Register { + username: username.to_string(), + password: "password".to_string(), + }, + &state, + db, + ) + .await; + + state + } + + #[tokio::test] + async fn forbidden_community_update() { + let db = test::get_database().await; + let owner = signed_in("Owner", &db).await; + let other = signed_in("Other", &db).await; + let (Response::Community(community), _) = handle( + Request::CreateCommunity { + name: "The Community".to_string(), + }, + &owner, + &db, + ) + .await + else { + panic!("community not created"); + }; + + let (response, _) = handle( + Request::UpdateCommunity { + community_id: community.id, + name: "Renamed".to_string(), + }, + &other, + &db, + ) + .await; + + assert!(matches!(response, Response::Error(CommonError::Forbidden))); + } + + #[tokio::test] + async fn delete_community_removes_messages() { + let db = test::get_database().await; + let owner = signed_in("Owner", &db).await; + let (Response::Community(community), _) = handle( + Request::CreateCommunity { + name: "The Community".to_string(), + }, + &owner, + &db, + ) + .await + else { + panic!("community not created"); + }; + handle( + Request::CreateMessage { + community_id: community.id.clone(), + body: "Tahinli".to_string(), + }, + &owner, + &db, + ) + .await; + + handle( + Request::DeleteCommunity { + community_id: community.id.clone(), + }, + &owner, + &db, + ) + .await; + + let conn = database::connect(&db).await.unwrap(); + let remaining = message::read_page(&community.id, None, &conn) + .await + .unwrap(); + + assert!(remaining.is_empty()); + } } diff --git a/crates/server/src/test.rs b/crates/server/src/test.rs index 165619e..220d0e0 100644 --- a/crates/server/src/test.rs +++ b/crates/server/src/test.rs @@ -1,8 +1,5 @@ use crate::database::{self, DB}; pub async fn get_database() -> DB { - let database = database::connect(":memory:").await.unwrap(); - database::migrate(&database).await.unwrap(); - - database + database::open(":memory:").await.unwrap() } diff --git a/crates/server/src/user.rs b/crates/server/src/user.rs index 0932eee..58aaa83 100644 --- a/crates/server/src/user.rs +++ b/crates/server/src/user.rs @@ -1,92 +1,109 @@ -use common::{model::User, validate::validate_username}; -use turso::Row; +use common::{error::Error as CommonError, model::User, validate::validate_username}; +use turso::{Connection, Row}; -use crate::{ - database::{DB, new_id}, - error::Error, -}; +use crate::{database::new_id, error::Error}; -fn from_row(row: &Row) -> Result { +pub fn from_row(row: &Row) -> Result { Ok(User { id: row.get(0)?, username: row.get(1)?, }) } -pub async fn create(username: &str, db: &DB) -> Result { - validate_username(username)?; - - let mut rows = db +pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result { + let mut rows = conn .query( - "INSERT INTO user (id, username) VALUES (?1, ?2) RETURNING id, username", - (new_id(), username), + "INSERT INTO user (id, username, password_hash) VALUES (?1, ?2, ?3) RETURNING id, username", + (new_id(), username, password_hash), ) .await?; - let row = rows.next().await?.ok_or(Error::NotFound)?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; from_row(&row) } -pub async fn read(user_id: &str, db: &DB) -> Result { - let mut rows = db +pub async fn read(user_id: &str, conn: &Connection) -> Result { + let mut rows = conn .query("SELECT id, username FROM user WHERE id = ?1", (user_id,)) .await?; - let row = rows.next().await?.ok_or(Error::NotFound)?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; from_row(&row) } -pub async fn read_by_username(username: &str, db: &DB) -> Result, Error> { - let mut rows = db +pub async fn by_username(username: &str, conn: &Connection) -> Result, Error> { + let mut rows = conn .query( - "SELECT id, username FROM user WHERE username = ?1 ORDER BY id", + "SELECT id, username FROM user WHERE username = ?1", (username,), ) .await?; - let mut users = Vec::new(); - while let Some(row) = rows.next().await? { - users.push(from_row(&row)?); - } + rows.next().await?.as_ref().map(from_row).transpose() +} + +pub async fn credentials( + username: &str, + conn: &Connection, +) -> Result, Error> { + let mut rows = conn + .query( + "SELECT id, username, password_hash FROM user WHERE username = ?1", + (username,), + ) + .await?; + let Some(row) = rows.next().await? else { + return Ok(None); + }; - Ok(users) + Ok(Some((from_row(&row)?, row.get(2)?))) } -pub async fn update(user_id: &str, username: &str, db: &DB) -> Result { +pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result { validate_username(username)?; - let mut rows = db + if by_username(username, conn) + .await? + .is_some_and(|existing| existing.id != user_id) + { + return Err(CommonError::Taken.into()); + } + + let mut rows = conn .query( "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING id, username", (user_id, username), ) .await?; - let row = rows.next().await?.ok_or(Error::NotFound)?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; from_row(&row) } -pub async fn delete(user_id: &str, db: &DB) -> Result { - let mut rows = db +pub async fn delete(user_id: &str, conn: &Connection) -> Result { + let mut rows = conn .query( "DELETE FROM user WHERE id = ?1 RETURNING id, username", (user_id,), ) .await?; - let row = rows.next().await?.ok_or(Error::NotFound)?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; from_row(&row) } #[cfg(test)] mod tests { - use crate::{error::Error, test, user}; + use common::error::Error as CommonError; + + use crate::{database, error::Error, test, user}; #[tokio::test] async fn create() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); - let user = user::create("Tahinli", &db).await.unwrap(); + let user = user::create("Tahinli", "hash", &conn).await.unwrap(); assert_eq!("Tahinli", user.username); } @@ -94,9 +111,10 @@ mod tests { #[tokio::test] async fn read() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); - let created_user = user::create("Tahinli", &db).await.unwrap(); - let searched_user = user::read(&created_user.id, &db).await.unwrap(); + let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); + let searched_user = user::read(&created_user.id, &conn).await.unwrap(); assert_eq!(created_user, searched_user); } @@ -104,25 +122,26 @@ mod tests { #[tokio::test] async fn read_by_username() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); - let user_1 = user::create("Tahinli", &db).await.unwrap(); - let user_2 = user::create("Tahinli", &db).await.unwrap(); - let _user_3 = user::create("Not Tahinli", &db).await.unwrap(); + let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); + let _other_user = user::create("Not Tahinli", "hash", &conn).await.unwrap(); - let searched_users = user::read_by_username("Tahinli", &db).await.unwrap(); + let searched_user = user::by_username("Tahinli", &conn).await.unwrap(); - assert_eq!(vec![user_1, user_2], searched_users); + assert_eq!(Some(created_user), searched_user); } #[tokio::test] async fn update() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); - let created_user = user::create("Tahinli", &db).await.unwrap(); - let updated_user = user::update(&created_user.id, "Not Tahinli", &db) + let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); + let updated_user = user::update(&created_user.id, "Not Tahinli", &conn) .await .unwrap(); - let searched_user = user::read(&created_user.id, &db).await.unwrap(); + let searched_user = user::read(&created_user.id, &conn).await.unwrap(); assert_eq!(created_user.id, searched_user.id); assert_eq!(updated_user, searched_user); @@ -132,18 +151,23 @@ mod tests { #[tokio::test] async fn update_on_missing_user() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); - let updated_user = user::update("missing", "Not Tahinli", &db).await; + let updated_user = user::update("missing", "Not Tahinli", &conn).await; - assert!(matches!(updated_user, Err(Error::NotFound))); + assert!(matches!( + updated_user, + Err(Error::Common(CommonError::NotFound)) + )); } #[tokio::test] async fn delete() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); - let created_user = user::create("Tahinli", &db).await.unwrap(); - let deleted_user = user::delete(&created_user.id, &db).await.unwrap(); + let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); + let deleted_user = user::delete(&created_user.id, &conn).await.unwrap(); assert_eq!(created_user, deleted_user); } diff --git a/crates/server/src/user_community.rs b/crates/server/src/user_community.rs index df8277c..fdb511e 100644 --- a/crates/server/src/user_community.rs +++ b/crates/server/src/user_community.rs @@ -1,7 +1,10 @@ -use crate::{database::DB, error::Error}; +use common::{error::Error as CommonError, model::User}; +use turso::Connection; -pub async fn join(user_id: &str, community_id: &str, db: &DB) -> Result<(), Error> { - db.execute( +use crate::{error::Error, user}; + +pub async fn join(user_id: &str, community_id: &str, conn: &Connection) -> Result<(), Error> { + conn.execute( "INSERT INTO user_community (user_id, community_id) VALUES (?1, ?2)", (user_id, community_id), ) @@ -10,8 +13,8 @@ pub async fn join(user_id: &str, community_id: &str, db: &DB) -> Result<(), Erro Ok(()) } -pub async fn leave(user_id: &str, community_id: &str, db: &DB) -> Result<(), Error> { - let deleted = db +pub async fn leave(user_id: &str, community_id: &str, conn: &Connection) -> Result<(), Error> { + let deleted = conn .execute( "DELETE FROM user_community WHERE user_id = ?1 AND community_id = ?2", (user_id, community_id), @@ -19,74 +22,79 @@ pub async fn leave(user_id: &str, community_id: &str, db: &DB) -> Result<(), Err .await?; if deleted == 0 { - return Err(Error::NotFound); + return Err(CommonError::NotFound.into()); } Ok(()) } -pub async fn is_user_in(user_id: &str, community_id: &str, db: &DB) -> Result { - let mut rows = db +pub async fn is_member( + user_id: &str, + community_id: &str, + conn: &Connection, +) -> Result { + let mut rows = conn .query( "SELECT COUNT(*) FROM user_community WHERE user_id = ?1 AND community_id = ?2", (user_id, community_id), ) .await?; - let row = rows.next().await?.ok_or(Error::NotFound)?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; let count: i64 = row.get(0)?; Ok(count > 0) } -pub async fn users_in(community_id: &str, db: &DB) -> Result, Error> { - let mut rows = db - .query( - "SELECT user_id FROM user_community WHERE community_id = ?1 ORDER BY user_id", - (community_id,), - ) - .await?; - - let mut user_ids = Vec::new(); - while let Some(row) = rows.next().await? { - user_ids.push(row.get(0)?); +pub async fn ensure_member( + user_id: &str, + community_id: &str, + conn: &Connection, +) -> Result<(), Error> { + if !is_member(user_id, community_id, conn).await? { + return Err(CommonError::Forbidden.into()); } - Ok(user_ids) + Ok(()) } -pub async fn communities_of(user_id: &str, db: &DB) -> Result, Error> { - let mut rows = db +pub async fn members(community_id: &str, conn: &Connection) -> Result, Error> { + let mut rows = conn .query( - "SELECT community_id FROM user_community WHERE user_id = ?1 ORDER BY community_id", - (user_id,), + "SELECT user.id, user.username FROM user JOIN user_community ON user_community.user_id = user.id WHERE user_community.community_id = ?1 ORDER BY user.id", + (community_id,), ) .await?; - let mut community_ids = Vec::new(); + let mut members = Vec::new(); while let Some(row) = rows.next().await? { - community_ids.push(row.get(0)?); + members.push(user::from_row(&row)?); } - Ok(community_ids) + Ok(members) } #[cfg(test)] mod tests { - use crate::{community, error::Error, test, user, user_community}; + use common::error::Error as CommonError; + + use crate::{community, database, error::Error, test, user, user_community}; #[tokio::test] async fn join() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); + let member = user::create("Not Tahinli", "hash", &conn).await.unwrap(); + let community = community::create("The Community", &owner.id, &conn) + .await + .unwrap(); - let user = user::create("Tahinli", &db).await.unwrap(); - let community = community::create("The Community", &db).await.unwrap(); - - user_community::join(&user.id, &community.id, &db) + user_community::join(&member.id, &community.id, &conn) .await .unwrap(); assert!( - user_community::is_user_in(&user.id, &community.id, &db) + user_community::is_member(&member.id, &community.id, &conn) .await .unwrap() ); @@ -95,16 +103,18 @@ mod tests { #[tokio::test] async fn join_again() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); + let community = community::create("The Community", &owner.id, &conn) + .await + .unwrap(); - let user = user::create("Tahinli", &db).await.unwrap(); - let community = community::create("The Community", &db).await.unwrap(); - - user_community::join(&user.id, &community.id, &db) + user_community::join(&owner.id, &community.id, &conn) .await .unwrap(); assert!( - user_community::join(&user.id, &community.id, &db) + user_community::join(&owner.id, &community.id, &conn) .await .is_err() ); @@ -113,19 +123,21 @@ mod tests { #[tokio::test] async fn leave() { let db = test::get_database().await; - - let user = user::create("Tahinli", &db).await.unwrap(); - let community = community::create("The Community", &db).await.unwrap(); - user_community::join(&user.id, &community.id, &db) + let conn = database::connect(&db).await.unwrap(); + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); + let community = community::create("The Community", &owner.id, &conn) + .await + .unwrap(); + user_community::join(&owner.id, &community.id, &conn) .await .unwrap(); - user_community::leave(&user.id, &community.id, &db) + user_community::leave(&owner.id, &community.id, &conn) .await .unwrap(); assert!( - !user_community::is_user_in(&user.id, &community.id, &db) + !user_community::is_member(&owner.id, &community.id, &conn) .await .unwrap() ); @@ -134,60 +146,67 @@ mod tests { #[tokio::test] async fn leave_again() { let db = test::get_database().await; - - let user = user::create("Tahinli", &db).await.unwrap(); - let community = community::create("The Community", &db).await.unwrap(); - user_community::join(&user.id, &community.id, &db) + let conn = database::connect(&db).await.unwrap(); + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); + let community = community::create("The Community", &owner.id, &conn) + .await + .unwrap(); + user_community::join(&owner.id, &community.id, &conn) .await .unwrap(); - user_community::leave(&user.id, &community.id, &db) + user_community::leave(&owner.id, &community.id, &conn) .await .unwrap(); - let leave = user_community::leave(&user.id, &community.id, &db).await; + let leave = user_community::leave(&owner.id, &community.id, &conn).await; - assert!(matches!(leave, Err(Error::NotFound))); + assert!(matches!(leave, Err(Error::Common(CommonError::NotFound)))); } #[tokio::test] - async fn users_in() { + async fn members() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); + let user_1 = user::create("Tahinli", "hash", &conn).await.unwrap(); + let user_2 = user::create("Not Tahinli", "hash", &conn).await.unwrap(); + let _user_3 = user::create("Third Tahinli", "hash", &conn).await.unwrap(); + let community = community::create("The Community", &user_1.id, &conn) + .await + .unwrap(); - let user_1 = user::create("Tahinli", &db).await.unwrap(); - let user_2 = user::create("Tahinli", &db).await.unwrap(); - let _user_3 = user::create("Tahinli", &db).await.unwrap(); - let community = community::create("The Community", &db).await.unwrap(); - - user_community::join(&user_1.id, &community.id, &db) + user_community::join(&user_1.id, &community.id, &conn) .await .unwrap(); - user_community::join(&user_2.id, &community.id, &db) + user_community::join(&user_2.id, &community.id, &conn) .await .unwrap(); - let users_in = user_community::users_in(&community.id, &db).await.unwrap(); + let members = user_community::members(&community.id, &conn).await.unwrap(); - assert_eq!(vec![user_1.id, user_2.id], users_in); + assert_eq!(vec![user_1, user_2], members); } #[tokio::test] async fn communities_of() { let db = test::get_database().await; + let conn = database::connect(&db).await.unwrap(); + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); + let community_1 = community::create("The Community", &owner.id, &conn) + .await + .unwrap(); + let community_2 = community::create("The Community", &owner.id, &conn) + .await + .unwrap(); - let user = user::create("Tahinli", &db).await.unwrap(); - let community_1 = community::create("The Community", &db).await.unwrap(); - let community_2 = community::create("The Community", &db).await.unwrap(); - let _community_3 = community::create("The Community", &db).await.unwrap(); - - user_community::join(&user.id, &community_1.id, &db) + user_community::join(&owner.id, &community_1.id, &conn) .await .unwrap(); - user_community::join(&user.id, &community_2.id, &db) + user_community::join(&owner.id, &community_2.id, &conn) .await .unwrap(); - let communities_of = user_community::communities_of(&user.id, &db).await.unwrap(); + let communities_of = community::communities_of(&owner.id, &conn).await.unwrap(); - assert_eq!(vec![community_1.id, community_2.id], communities_of); + assert_eq!(vec![community_1, community_2], communities_of); } }