use std::collections::BTreeMap; use common::{ error::Error as CommonError, event::Event, model::{AdminAction, CallLog, Id, Message, Presence, Rank, User}, permission, share::Kind as ShareKind, }; use crate::{ call::Cx, db::{self, Connection, community::Kind}, error::{ServerError, ensure}, hub::{Client, Hub}, publish::{Broadcast, To}, rate_limit::RateLimit, rooms::{Departure, Rooms}, }; pub(crate) async fn limit_logins( rate_limit: &RateLimit, connection: Option<&quinn::Connection>, db: &Connection, ) -> Result<(), ServerError> { let limit = db::settings::read(db).await?.logins_per_minute; let ip = connection .map(|connection| connection.remote_address().ip().to_string()) .unwrap_or_default(); Ok(rate_limit.allow(&ip, limit)?) } pub(crate) async fn effective_presence( hub: &Hub, user_id: Id, db: &Connection, ) -> Result { if !hub.is_online(user_id) { return Ok(Presence::Offline); } db::user::presence(user_id, db).await } pub async fn presence_changed( hub: &Hub, user_id: Id, db: &Connection, ) -> Result, ServerError> { let presence = effective_presence(hub, user_id, db).await?; let event = Event::PresenceChanged { user_id, presence }; Ok(vec![Broadcast::new(To::Related(user_id), event)]) } pub(crate) async fn introduce( user_id: Id, others: &[Id], cx: &mut Cx<'_>, ) -> Result<(), ServerError> { let hub = &cx.sh.services.hub; let presence = effective_presence(hub, user_id, cx.db).await?; for &other in others { if other == user_id { continue; } let theirs = effective_presence(hub, other, cx.db).await?; cx.emit( To::User(other), Event::PresenceChanged { user_id, presence }, ); cx.emit( To::User(user_id), Event::PresenceChanged { user_id: other, presence: theirs, }, ); } Ok(()) } pub(crate) async fn leave_user_voice( rooms: &Rooms, user_id: Id, db: &Connection, ) -> Result, ServerError> { match rooms.leave_user(user_id) { Some(departure) => departed(departure, db).await, None => Ok(Vec::new()), } } pub(crate) async fn leave_room_voice( rooms: &Rooms, community_id: Id, user_id: Id, db: &Connection, ) -> Result, ServerError> { match rooms.leave_room(community_id, user_id) { Some(departure) => departed(departure, db).await, None => Ok(Vec::new()), } } pub(crate) async fn voice_muted( community_id: Option, user_id: Id, muted: bool, db: &Connection, ) -> Result { let mut user_ids = vec![user_id]; if let Some(community_id) = community_id && !db::user::is_ghost(user_id, db).await? { user_ids.extend(db::member::member_ids(community_id, db).await?); } let event = Event::VoiceMuted { community_id, user_id, muted, }; Ok(Broadcast::new(To::Users(user_ids), event)) } pub(crate) async fn voice_closed( rooms: &Rooms, community_id: Id, db: &Connection, ) -> Result, ServerError> { let mut broadcasts = Vec::new(); for departure in rooms.close_room(community_id) { broadcasts.extend(departed(departure, db).await?); } Ok(broadcasts) } pub(crate) async fn delete_community(community_id: Id, cx: &mut Cx<'_>) -> Result<(), ServerError> { let member_ids = db::member::member_ids(community_id, cx.db).await?; let closed = voice_closed(&cx.sh.services.rooms, community_id, cx.db).await?; cx.out.extend(closed); db::community::delete(community_id, cx.db).await?; cx.emit( To::Users(member_ids), Event::CommunityDeleted { community_id }, ); Ok(()) } pub(crate) async fn call_ended( community_id: Id, user_id: Id, call: Option, db: &Connection, ) -> Result, ServerError> { let Some(call) = call else { return Ok(Vec::new()); }; if db::community::kind_of(community_id, db).await? != Some(Kind::Direct) { return Ok(Vec::new()); } let created = db::message::create_call_log(community_id, user_id, call, db).await?; Ok(vec![message_event(&created, Event::MessageCreated)]) } pub async fn departed( mut departure: Departure, db: &Connection, ) -> Result, ServerError> { let mut broadcasts = shares_ended(&mut departure); if departure.quiet { return Ok(broadcasts); } let Departure { community_id, user_id, ghost_seconds, call_log, .. } = departure; let Some(seconds) = ghost_seconds else { broadcasts.extend(call_ended(community_id, user_id, call_log, db).await?); let event = Event::VoiceLeft { community_id, user_id, }; broadcasts.push(Broadcast::new(To::Community(community_id), event)); return Ok(broadcasts); }; record_ghost_voice(user_id, community_id, seconds, db).await?; let event = Event::VoiceLeft { community_id, user_id, }; broadcasts.push(Broadcast::new(To::User(user_id), event)); Ok(broadcasts) } pub(crate) fn share_ended(community_id: Id, user_id: Id, kind: ShareKind) -> Broadcast { let event = Event::ShareStopped { community_id, user_id, kind, }; Broadcast::new(To::Community(community_id), event) } pub(crate) fn shares_ended(departure: &mut Departure) -> Vec { let mut broadcasts: Vec = departure .shares .iter() .map(|kind| share_ended(departure.community_id, departure.user_id, *kind)) .collect(); broadcasts.append(&mut departure.media); broadcasts } pub(crate) fn messages_deleted(rows: Vec<(Id, Id)>) -> Vec { let mut deleted: BTreeMap> = BTreeMap::new(); for (community_id, message_id) in rows { deleted.entry(community_id).or_default().push(message_id); } deleted .into_iter() .map(|(community_id, ids)| { let event = Event::MessagesDeleted { community_id, ids }; Broadcast::new(To::Community(community_id), event) }) .collect() } pub(crate) async fn authenticated(client: &Client, db: &Connection) -> Result { let me = client.me.as_ref().ok_or(CommonError::Unauthenticated)?; Ok(db::session::user_of(me.session_id, db) .await? .ok_or(CommonError::Unauthenticated)?) } pub async fn actor_rank( me: &User, community_id: Id, db: &Connection, ) -> Result, ServerError> { let rank = db::member::rank(me.id, community_id, db).await?; Ok(permission::effective_rank(me.role, rank)) } pub(crate) async fn managed(me: &User, user_id: Id, db: &Connection) -> Result { let target = db::user::read(user_id, db).await?; ensure(permission::can_manage_user( me.role, me.id == user_id, target.role, ))?; Ok(target) } pub(crate) async fn allowed( me: &User, community_id: Id, db: &Connection, check: fn(Option) -> bool, ) -> Result<(), ServerError> { ensure(check(actor_rank(me, community_id, db).await?)) } pub(crate) async fn is_outsider( user_id: Id, community_id: Id, db: &Connection, ) -> Result { Ok(db::member::rank(user_id, community_id, db).await?.is_none()) } pub(crate) async fn ensure_editable(community_id: Id, db: &Connection) -> Result<(), ServerError> { let kind = db::community::kind_of(community_id, db) .await? .ok_or(CommonError::NotFound)?; ensure(kind == Kind::Group) } pub(crate) fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast { let mut message = message.clone(); if let Some(reply) = &mut message.reply { reply.redact(); } Broadcast::new(To::Community(message.community_id), event(message)) } pub(crate) fn voice_joined(community_id: Id, user_id: Id, muted: bool) -> Vec { let mut broadcasts = vec![Broadcast::new( To::Community(community_id), Event::VoiceJoined { community_id, user_id, }, )]; if muted { broadcasts.push(Broadcast::new( To::Community(community_id), Event::VoiceMuted { community_id: Some(community_id), user_id, muted, }, )); } broadcasts } pub(crate) async fn record_ghost_voice( user_id: Id, community_id: Id, seconds: u64, db: &Connection, ) -> Result<(), ServerError> { let community = db::community::label(community_id, db).await?; db::log::record_admin( Some(user_id), None, Some(&community), &AdminAction::GhostVoice { seconds }, db, ) .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, Me}, db::{self, Db}, hub::{Client, Signed}, network::{Services, Shared}, request::authenticated, test, }; fn shared(db: &Db, services: &Services) -> Shared { Shared { db: db.clone(), services: services.clone(), directory: test::directory(), backups: test::directory(), updates: test::directory(), } } 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::User(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::default(); 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::default(); 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::default(); 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::default(); 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::default(); 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::default(); 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) )); } }