mod admin; mod community; mod message; mod release; pub(crate) mod shared; mod social; mod stats; mod user; mod voice; use std::{future::Future, sync::Arc}; use common::{ call::{Call, Gate, GetSettings, Login, Register, Request}, error::Error, event::Event, frame::{self, DOWN_MAX}, model::User, permission, }; use crate::{ db::{self, Connection}, error::{ServerError, ensure}, hub::Client, network::Shared, publish::{Broadcast, To}, }; use shared::authenticated; pub(crate) struct Cx<'a> { pub client: &'a Arc, pub sh: &'a Shared, pub db: &'a Connection, pub out: Vec, } impl<'a> Cx<'a> { pub(crate) fn new(client: &'a Arc, sh: &'a Shared, db: &'a Connection) -> Self { Self { client, sh, db, out: Vec::new(), } } pub fn emit(&mut self, to: To, event: Event) { self.out.push(Broadcast::new(to, event)); } } pub(crate) trait Handle: Call { fn handle( self, me: User, cx: &mut Cx<'_>, ) -> impl Future> + Send; } async fn gate(gate: Gate, cx: &Cx<'_>) -> Result { let user = authenticated(cx.client, cx.db).await?; match gate { Gate::Guest => Err(Error::Server.into()), Gate::User => Ok(user), Gate::Builder => { ensure(permission::is_builder(user.role))?; Ok(user) } } } async fn serve(call: C, cx: &mut Cx<'_>) -> Vec { let db = cx.db; let reply = match call.validate() { Ok(()) => { db::atomic(db, async { let me = gate(C::GATE, cx).await?; call.handle(me, cx).await }) .await } Err(error) => Err(error.into()), }; if reply.is_err() { cx.out.clear(); } encode::(reply) } pub(crate) fn encode(reply: Result) -> Vec { let reply = reply.map_err(Error::from); frame::encode(&reply, DOWN_MAX).unwrap_or_else(|_| { frame::encode(&Err::(Error::Server), DOWN_MAX).expect("small") }) } pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec { match request { Request::GetSettings(_) => encode::(db::settings::read(cx.db).await), Request::GetUser(call) => serve(call, cx).await, Request::UpdateUser(call) => serve(call, cx).await, Request::UpdateStatus(call) => serve(call, cx).await, Request::UpdateHue(call) => serve(call, cx).await, Request::UpdatePresence(call) => serve(call, cx).await, Request::ListPresences(call) => serve(call, cx).await, Request::UpdateAvatar(call) => serve(call, cx).await, Request::RemoveAvatar(call) => serve(call, cx).await, Request::GetAvatar(call) => serve(call, cx).await, Request::ListSessions(call) => serve(call, cx).await, Request::RevokeSession(call) => serve(call, cx).await, Request::CreateCommunity(call) => serve(call, cx).await, Request::GetCommunity(call) => serve(call, cx).await, Request::UpdateCommunity(call) => serve(call, cx).await, Request::UpdateCommunityAvatar(call) => serve(call, cx).await, Request::DeleteCommunity(call) => serve(call, cx).await, Request::LeaveCommunity(call) => serve(call, cx).await, Request::ListCommunities(call) => serve(call, cx).await, Request::ListMembers(call) => serve(call, cx).await, Request::Kick(call) => serve(call, cx).await, Request::BanMember(call) => serve(call, cx).await, Request::Unban(call) => serve(call, cx).await, Request::ListBans(call) => serve(call, cx).await, Request::SetRank(call) => serve(call, cx).await, Request::ListLogs(call) => serve(call, cx).await, Request::CreateMessage(call) => serve(call, cx).await, Request::ForwardMessages(call) => serve(call, cx).await, Request::UpdateMessage(call) => serve(call, cx).await, Request::DeleteMessage(call) => serve(call, cx).await, Request::CreatePoll(call) => serve(call, cx).await, Request::Vote(call) => serve(call, cx).await, Request::ClosePoll(call) => serve(call, cx).await, Request::MyVotes(call) => serve(call, cx).await, Request::React(call) => serve(call, cx).await, Request::Pin(call) => serve(call, cx).await, Request::ListPins(call) => serve(call, cx).await, Request::ListEdits(call) => serve(call, cx).await, Request::ListMessages(call) => serve(call, cx).await, Request::ListUnreads(call) => serve(call, cx).await, Request::MarkRead(call) => serve(call, cx).await, Request::Typing(call) => serve(call, cx).await, Request::FindUser(call) => serve(call, cx).await, Request::OpenDirect(call) => serve(call, cx).await, Request::OpenNotes(call) => serve(call, cx).await, Request::ListFriends(call) => serve(call, cx).await, Request::AddFriend(call) => serve(call, cx).await, Request::AcceptFriend(call) => serve(call, cx).await, Request::RemoveFriend(call) => serve(call, cx).await, Request::Invite(call) => serve(call, cx).await, Request::ListInvitations(call) => serve(call, cx).await, Request::AcceptInvitation(call) => serve(call, cx).await, Request::DeclineInvitation(call) => serve(call, cx).await, Request::ReportMessage(call) => serve(call, cx).await, Request::ReportUser(call) => serve(call, cx).await, Request::ListReports(call) => serve(call, cx).await, Request::HandleReport(call) => serve(call, cx).await, Request::JoinVoice(call) => serve(call, cx).await, Request::LeaveVoice(call) => serve(call, cx).await, Request::StartShare(call) => serve(call, cx).await, Request::StopShare(call) => serve(call, cx).await, Request::ListShares(call) => serve(call, cx).await, Request::WatchShare(call) => serve(call, cx).await, Request::UnwatchShare(call) => serve(call, cx).await, Request::RequestKeyframe(call) => serve(call, cx).await, Request::ReportLoss(call) => serve(call, cx).await, Request::DeclineCall(call) => serve(call, cx).await, Request::ListVoiceParticipants(call) => serve(call, cx).await, Request::ListVoiceRooms(call) => serve(call, cx).await, Request::KickFromVoice(call) => serve(call, cx).await, Request::ServerMute(call) => serve(call, cx).await, Request::Register(_) => encode::(Err(Error::Server.into())), Request::Login(_) => encode::(Err(Error::Server.into())), Request::Logout(call) => serve(call, cx).await, Request::DeleteUser(call) => serve(call, cx).await, Request::WatchCommunity(call) => serve(call, cx).await, Request::ListUsers(call) => serve(call, cx).await, Request::ListAdminLogs(call) => serve(call, cx).await, Request::ListUserFriends(call) => serve(call, cx).await, Request::GetOverview(call) => serve(call, cx).await, Request::SuspendUser(call) => serve(call, cx).await, Request::RevokeSessions(call) => serve(call, cx).await, Request::ResetPassword(call) => serve(call, cx).await, Request::ClearProfile(call) => serve(call, cx).await, Request::ListAllCommunities(call) => serve(call, cx).await, Request::TransferOwnership(call) => serve(call, cx).await, Request::UpdateServerSettings(call) => serve(call, cx).await, Request::CreateUser(call) => serve(call, cx).await, Request::RenameUser(call) => serve(call, cx).await, Request::TimeoutUser(call) => serve(call, cx).await, Request::BanUser(call) => serve(call, cx).await, Request::ListServerBans(call) => serve(call, cx).await, Request::RemoveServerBan(call) => serve(call, cx).await, Request::CreateInviteCode(call) => serve(call, cx).await, Request::ListInviteCodes(call) => serve(call, cx).await, Request::DeleteInviteCode(call) => serve(call, cx).await, Request::SearchMessages(call) => serve(call, cx).await, Request::SearchCommunity(call) => serve(call, cx).await, Request::PurgeUser(call) => serve(call, cx).await, Request::SetCommunityVoice(call) => serve(call, cx).await, Request::ListAttachments(call) => serve(call, cx).await, Request::DeleteAttachment(call) => serve(call, cx).await, Request::GetStorageUsage(call) => serve(call, cx).await, Request::GetDailyStats(call) => serve(call, cx).await, Request::SetGhost(call) => serve(call, cx).await, Request::RestartServer(call) => serve(call, cx).await, Request::CreateBackup(call) => serve(call, cx).await, Request::ListBackups(call) => serve(call, cx).await, Request::DeleteBackup(call) => serve(call, cx).await, Request::FollowStats(call) => serve(call, cx).await, Request::PushStats(call) => serve(call, cx).await, Request::GetServerStats(call) => serve(call, cx).await, Request::ListReleases(call) => serve(call, cx).await, Request::ListUpdateClients(call) => serve(call, cx).await, Request::PublishRelease(call) => serve(call, cx).await, Request::ImportRelease(call) => serve(call, cx).await, Request::GetForge(call) => serve(call, cx).await, Request::CreateTag(call) => serve(call, cx).await, Request::SetReleaseRequired(call) => serve(call, cx).await, } } #[cfg(test)] mod tests { use std::sync::Arc; use common::{ call::{ AcceptFriend, AcceptInvitation, AddFriend, CreateCommunity, CreateMessage, DeleteCommunity, FindUser, Invite, Kick, LeaveCommunity, ListCommunities, ListFriends, UpdateCommunity, }, error::Error as CommonError, model::{Id, Role}, }; use crate::{ authentication::token_hash, call::{Cx, Handle, shared::authenticated}, db::{self, Db}, hub::{Client, Signed}, network::{Services, Shared}, test, }; fn shared(db: &Db, services: &Services) -> Shared { Shared { db: db.clone(), services: services.clone(), attachments: test::directory(), backups: test::directory(), releases: Default::default(), } } async fn call( call: C, client: &Arc, db: &Db, services: &Services, ) -> Result { let shared = shared(db, services); let conn = db.lock().await.unwrap(); let me = authenticated(client, &conn).await?; let mut cx = Cx::new(client, &shared, &conn); Ok(call.handle(me, &mut cx).await?) } async fn signed_in(username: &str, db: &Db) -> Arc { signed_in_as(username, Role::User, db).await } async fn signed_in_as(username: &str, role: Role, db: &Db) -> Arc { let conn = db.lock().await.unwrap(); let user = db::user::create(username, "hash", role, &conn) .await .unwrap(); let session_id = db::session::insert(&token_hash(username), user.id, &conn) .await .unwrap(); Client::detached(Some(Signed { user_id: user.id, session_id, })) } async fn invite_and_accept( community_id: Id, owner: &Arc, member: &Arc, username: &str, db: &Db, services: &Services, ) { let member_user = call( FindUser { username: username.to_string(), }, owner, db, services, ) .await .unwrap(); call( Invite { community_id, user_id: member_user.id, }, owner, db, services, ) .await .unwrap(); call(AcceptInvitation { community_id }, member, db, services) .await .unwrap(); } #[tokio::test] async fn plain_member_cannot_rename() { let db = test::db().await; let services = Services::new(test::directory()); let owner = signed_in("Owner", &db).await; let member = signed_in("Member", &db).await; let community = call( CreateCommunity { name: "The Community".to_string(), }, &owner, &db, &services, ) .await .unwrap(); invite_and_accept(community.id, &owner, &member, "Member", &db, &services).await; let response = call( UpdateCommunity { community_id: community.id, name: "Renamed".to_string(), }, &member, &db, &services, ) .await; assert!(matches!(response, Err(CommonError::Forbidden))); } #[tokio::test] async fn accepted_friend_request_befriends_both() { let db = test::db().await; let services = Services::new(test::directory()); let first = signed_in("First", &db).await; let second = signed_in("Second", &db).await; let first_user = call( FindUser { username: "First".to_string(), }, &second, &db, &services, ) .await .unwrap(); let second_user = call( FindUser { username: "Second".to_string(), }, &first, &db, &services, ) .await .unwrap(); call( AddFriend { user_id: second_user.id, }, &first, &db, &services, ) .await .unwrap(); call( AcceptFriend { user_id: first_user.id, }, &second, &db, &services, ) .await .unwrap(); let first_friends = call(ListFriends, &first, &db, &services).await.unwrap(); let second_friends = call(ListFriends, &second, &db, &services).await.unwrap(); assert_eq!(vec![second_user], first_friends.friends); assert_eq!(vec![first_user], second_friends.friends); } #[tokio::test] async fn invite_and_accept_makes_member() { let db = test::db().await; let services = Services::new(test::directory()); let owner = signed_in("Owner", &db).await; let member = signed_in("Member", &db).await; let community = call( CreateCommunity { name: "The Community".to_string(), }, &owner, &db, &services, ) .await .unwrap(); invite_and_accept(community.id, &owner, &member, "Member", &db, &services).await; let communities = call(ListCommunities, &member, &db, &services) .await .unwrap(); assert_eq!(vec![community], communities); } #[tokio::test] async fn delete_community_removes_messages() { let db = test::db().await; let services = Services::new(test::directory()); let owner = signed_in("Owner", &db).await; let community = call( CreateCommunity { name: "The Community".to_string(), }, &owner, &db, &services, ) .await .unwrap(); call( CreateMessage { community_id: community.id, body: "Tahinli".to_string(), attachments: Vec::new(), reply_to: None, }, &owner, &db, &services, ) .await .unwrap(); call( DeleteCommunity { community_id: community.id, }, &owner, &db, &services, ) .await .unwrap(); let conn = db.lock().await.unwrap(); let remaining = db::message::read_page(community.id, None, false, &conn) .await .unwrap(); assert!(remaining.is_empty()); } async fn group(owner: &Arc, db: &Db, services: &Services) -> Id { call( CreateCommunity { name: "The Community".to_string(), }, owner, db, services, ) .await .unwrap() .id } async fn user_id(username: &str, by: &Arc, db: &Db, services: &Services) -> Id { call( FindUser { username: username.to_string(), }, by, db, services, ) .await .unwrap() .id } #[tokio::test] async fn kick_of_non_member_is_not_found() { let db = test::db().await; let services = Services::new(test::directory()); let owner = signed_in("Owner", &db).await; signed_in("Outsider", &db).await; let community_id = group(&owner, &db, &services).await; let outsider = user_id("Outsider", &owner, &db, &services).await; let kick = Kick { community_id, user_id: outsider, reason: None, }; assert!(matches!( call(kick, &owner, &db, &services).await, Err(CommonError::NotFound) )); } #[tokio::test] async fn builder_cannot_leave_owned_group() { let db = test::db().await; let services = Services::new(test::directory()); let builder = signed_in_as("Builder", Role::Builder, &db).await; let community_id = group(&builder, &db, &services).await; let leave = LeaveCommunity { community_id }; assert!(matches!( call(leave, &builder, &db, &services).await, Err(CommonError::Forbidden) )); } }