forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

request.rs669 lines, 17.4 KiBHistoryRawDownload
1use std::collections::BTreeMap;
2
3use common::{
4 error::Error as CommonError,
5 event::Event,
6 model::{AdminAction, CallLog, Id, Message, Presence, Rank, User},
7 permission,
8 share::Kind as ShareKind,
9};
10
11use crate::{
12 call::Cx,
13 db::{self, Connection, community::Kind},
14 error::{ServerError, ensure},
15 hub::{Client, Hub},
16 publish::{Broadcast, To},
17 rate_limit::RateLimit,
18 rooms::{Departure, Rooms},
19};
20
21pub(crate) async fn limit_logins(
22 rate_limit: &RateLimit,
23 connection: Option<&quinn::Connection>,
24 db: &Connection,
25) -> Result<(), ServerError> {
26 let limit = db::settings::read(db).await?.logins_per_minute;
27
28 let ip = connection
29 .map(|connection| connection.remote_address().ip().to_string())
30 .unwrap_or_default();
31
32 Ok(rate_limit.allow(&ip, limit)?)
33}
34
35pub(crate) async fn effective_presence(
36 hub: &Hub,
37 user_id: Id,
38 db: &Connection,
39) -> Result<Presence, ServerError> {
40 if !hub.is_online(user_id) {
41 return Ok(Presence::Offline);
42 }
43
44 db::user::presence(user_id, db).await
45}
46
47pub async fn presence_changed(
48 hub: &Hub,
49 user_id: Id,
50 db: &Connection,
51) -> Result<Vec<Broadcast>, ServerError> {
52 let presence = effective_presence(hub, user_id, db).await?;
53 let event = Event::PresenceChanged { user_id, presence };
54
55 Ok(vec![Broadcast::new(To::Related(user_id), event)])
56}
57
58pub(crate) async fn introduce(
59 user_id: Id,
60 others: &[Id],
61 cx: &mut Cx<'_>,
62) -> Result<(), ServerError> {
63 let hub = &cx.sh.services.hub;
64 let presence = effective_presence(hub, user_id, cx.db).await?;
65 for &other in others {
66 if other == user_id {
67 continue;
68 }
69 let theirs = effective_presence(hub, other, cx.db).await?;
70 cx.emit(
71 To::User(other),
72 Event::PresenceChanged { user_id, presence },
73 );
74 cx.emit(
75 To::User(user_id),
76 Event::PresenceChanged {
77 user_id: other,
78 presence: theirs,
79 },
80 );
81 }
82
83 Ok(())
84}
85
86pub(crate) async fn leave_user_voice(
87 rooms: &Rooms,
88 user_id: Id,
89 db: &Connection,
90) -> Result<Vec<Broadcast>, ServerError> {
91 match rooms.leave_user(user_id) {
92 Some(departure) => departed(departure, db).await,
93 None => Ok(Vec::new()),
94 }
95}
96
97pub(crate) async fn leave_room_voice(
98 rooms: &Rooms,
99 community_id: Id,
100 user_id: Id,
101 db: &Connection,
102) -> Result<Vec<Broadcast>, ServerError> {
103 match rooms.leave_room(community_id, user_id) {
104 Some(departure) => departed(departure, db).await,
105 None => Ok(Vec::new()),
106 }
107}
108
109pub(crate) async fn voice_muted(
110 community_id: Option<Id>,
111 user_id: Id,
112 muted: bool,
113 db: &Connection,
114) -> Result<Broadcast, ServerError> {
115 let mut user_ids = vec![user_id];
116 if let Some(community_id) = community_id
117 && !db::user::is_ghost(user_id, db).await?
118 {
119 user_ids.extend(db::member::member_ids(community_id, db).await?);
120 }
121 let event = Event::VoiceMuted {
122 community_id,
123 user_id,
124 muted,
125 };
126
127 Ok(Broadcast::new(To::Users(user_ids), event))
128}
129
130pub(crate) async fn voice_closed(
131 rooms: &Rooms,
132 community_id: Id,
133 db: &Connection,
134) -> Result<Vec<Broadcast>, ServerError> {
135 let mut broadcasts = Vec::new();
136 for departure in rooms.close_room(community_id) {
137 broadcasts.extend(departed(departure, db).await?);
138 }
139
140 Ok(broadcasts)
141}
142
143pub(crate) async fn delete_community(community_id: Id, cx: &mut Cx<'_>) -> Result<(), ServerError> {
144 let member_ids = db::member::member_ids(community_id, cx.db).await?;
145 let closed = voice_closed(&cx.sh.services.rooms, community_id, cx.db).await?;
146 cx.out.extend(closed);
147 db::community::delete(community_id, cx.db).await?;
148 cx.emit(
149 To::Users(member_ids),
150 Event::CommunityDeleted { community_id },
151 );
152
153 Ok(())
154}
155
156pub(crate) async fn call_ended(
157 community_id: Id,
158 user_id: Id,
159 call: Option<CallLog>,
160 db: &Connection,
161) -> Result<Vec<Broadcast>, ServerError> {
162 let Some(call) = call else {
163 return Ok(Vec::new());
164 };
165 if db::community::kind_of(community_id, db).await? != Some(Kind::Direct) {
166 return Ok(Vec::new());
167 }
168 let created = db::message::create_call_log(community_id, user_id, call, db).await?;
169
170 Ok(vec![message_event(&created, Event::MessageCreated)])
171}
172
173pub async fn departed(
174 mut departure: Departure,
175 db: &Connection,
176) -> Result<Vec<Broadcast>, ServerError> {
177 let mut broadcasts = shares_ended(&mut departure);
178 if departure.quiet {
179 return Ok(broadcasts);
180 }
181 let Departure {
182 community_id,
183 user_id,
184 ghost_seconds,
185 call_log,
186 ..
187 } = departure;
188 let Some(seconds) = ghost_seconds else {
189 broadcasts.extend(call_ended(community_id, user_id, call_log, db).await?);
190 let event = Event::VoiceLeft {
191 community_id,
192 user_id,
193 };
194 broadcasts.push(Broadcast::new(To::Community(community_id), event));
195
196 return Ok(broadcasts);
197 };
198 record_ghost_voice(user_id, community_id, seconds, db).await?;
199 let event = Event::VoiceLeft {
200 community_id,
201 user_id,
202 };
203 broadcasts.push(Broadcast::new(To::User(user_id), event));
204
205 Ok(broadcasts)
206}
207
208pub(crate) fn share_ended(community_id: Id, user_id: Id, kind: ShareKind) -> Broadcast {
209 let event = Event::ShareStopped {
210 community_id,
211 user_id,
212 kind,
213 };
214
215 Broadcast::new(To::Community(community_id), event)
216}
217
218pub(crate) fn shares_ended(departure: &mut Departure) -> Vec<Broadcast> {
219 let mut broadcasts: Vec<Broadcast> = departure
220 .shares
221 .iter()
222 .map(|kind| share_ended(departure.community_id, departure.user_id, *kind))
223 .collect();
224 broadcasts.append(&mut departure.media);
225
226 broadcasts
227}
228
229pub(crate) fn messages_deleted(rows: Vec<(Id, Id)>) -> Vec<Broadcast> {
230 let mut deleted: BTreeMap<Id, Vec<Id>> = BTreeMap::new();
231 for (community_id, message_id) in rows {
232 deleted.entry(community_id).or_default().push(message_id);
233 }
234
235 deleted
236 .into_iter()
237 .map(|(community_id, ids)| {
238 let event = Event::MessagesDeleted { community_id, ids };
239 Broadcast::new(To::Community(community_id), event)
240 })
241 .collect()
242}
243
244pub(crate) async fn authenticated(client: &Client, db: &Connection) -> Result<User, ServerError> {
245 let me = client.me.as_ref().ok_or(CommonError::Unauthenticated)?;
246
247 Ok(db::session::user_of(me.session_id, db)
248 .await?
249 .ok_or(CommonError::Unauthenticated)?)
250}
251
252pub async fn actor_rank(
253 me: &User,
254 community_id: Id,
255 db: &Connection,
256) -> Result<Option<Rank>, ServerError> {
257 let rank = db::member::rank(me.id, community_id, db).await?;
258
259 Ok(permission::effective_rank(me.role, rank))
260}
261
262pub(crate) async fn managed(me: &User, user_id: Id, db: &Connection) -> Result<User, ServerError> {
263 let target = db::user::read(user_id, db).await?;
264 ensure(permission::can_manage_user(
265 me.role,
266 me.id == user_id,
267 target.role,
268 ))?;
269
270 Ok(target)
271}
272
273pub(crate) async fn allowed(
274 me: &User,
275 community_id: Id,
276 db: &Connection,
277 check: fn(Option<Rank>) -> bool,
278) -> Result<(), ServerError> {
279 ensure(check(actor_rank(me, community_id, db).await?))
280}
281
282pub(crate) async fn is_outsider(
283 user_id: Id,
284 community_id: Id,
285 db: &Connection,
286) -> Result<bool, ServerError> {
287 Ok(db::member::rank(user_id, community_id, db).await?.is_none())
288}
289
290pub(crate) async fn ensure_editable(community_id: Id, db: &Connection) -> Result<(), ServerError> {
291 let kind = db::community::kind_of(community_id, db)
292 .await?
293 .ok_or(CommonError::NotFound)?;
294
295 ensure(kind == Kind::Group)
296}
297
298pub(crate) fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast {
299 let mut message = message.clone();
300 if let Some(reply) = &mut message.reply {
301 reply.redact();
302 }
303
304 Broadcast::new(To::Community(message.community_id), event(message))
305}
306
307pub(crate) fn voice_joined(community_id: Id, user_id: Id, muted: bool) -> Vec<Broadcast> {
308 let mut broadcasts = vec![Broadcast::new(
309 To::Community(community_id),
310 Event::VoiceJoined {
311 community_id,
312 user_id,
313 },
314 )];
315 if muted {
316 broadcasts.push(Broadcast::new(
317 To::Community(community_id),
318 Event::VoiceMuted {
319 community_id: Some(community_id),
320 user_id,
321 muted,
322 },
323 ));
324 }
325
326 broadcasts
327}
328
329pub(crate) async fn record_ghost_voice(
330 user_id: Id,
331 community_id: Id,
332 seconds: u64,
333 db: &Connection,
334) -> Result<(), ServerError> {
335 let community = db::community::label(community_id, db).await?;
336 db::log::record_admin(
337 Some(user_id),
338 None,
339 Some(&community),
340 &AdminAction::GhostVoice { seconds },
341 db,
342 )
343 .await
344}
345
346#[cfg(test)]
347mod tests {
348 use std::sync::Arc;
349
350 use common::{
351 call::{
352 AcceptFriend, AcceptInvitation, AddFriend, CreateCommunity, CreateMessage,
353 DeleteCommunity, FindUser, Invite, Kick, LeaveCommunity, ListCommunities, ListFriends,
354 UpdateCommunity,
355 },
356 error::Error as CommonError,
357 model::{Id, Role},
358 };
359
360 use crate::{
361 authentication::token_hash,
362 call::{Cx, Handle, Me},
363 db::{self, Db},
364 hub::{Client, Signed},
365 network::{Services, Shared},
366 request::authenticated,
367 test,
368 };
369
370 fn shared(db: &Db, services: &Services) -> Shared {
371 Shared {
372 db: db.clone(),
373 services: services.clone(),
374 directory: test::directory(),
375 backups: test::directory(),
376 releases: Default::default(),
377 }
378 }
379
380 async fn call<C: Handle>(
381 call: C,
382 client: &Arc<Client>,
383 db: &Db,
384 services: &Services,
385 ) -> Result<C::Reply, CommonError> {
386 let shared = shared(db, services);
387 let conn = db.lock().await.unwrap();
388 let me = authenticated(client, &conn).await?;
389 let mut cx = Cx::new(client, &shared, &conn);
390
391 Ok(call.handle(Me::User(me), &mut cx).await?)
392 }
393
394 async fn signed_in(username: &str, db: &Db) -> Arc<Client> {
395 signed_in_as(username, Role::User, db).await
396 }
397
398 async fn signed_in_as(username: &str, role: Role, db: &Db) -> Arc<Client> {
399 let conn = db.lock().await.unwrap();
400 let user = db::user::create(username, "hash", role, &conn)
401 .await
402 .unwrap();
403 let session_id = db::session::insert(&token_hash(username), user.id, &conn)
404 .await
405 .unwrap();
406
407 Client::detached(Some(Signed {
408 user_id: user.id,
409 session_id,
410 }))
411 }
412
413 async fn invite_and_accept(
414 community_id: Id,
415 owner: &Arc<Client>,
416 member: &Arc<Client>,
417 username: &str,
418 db: &Db,
419 services: &Services,
420 ) {
421 let member_user = call(
422 FindUser {
423 username: username.to_string(),
424 },
425 owner,
426 db,
427 services,
428 )
429 .await
430 .unwrap();
431 call(
432 Invite {
433 community_id,
434 user_id: member_user.id,
435 },
436 owner,
437 db,
438 services,
439 )
440 .await
441 .unwrap();
442 call(AcceptInvitation { community_id }, member, db, services)
443 .await
444 .unwrap();
445 }
446
447 #[tokio::test]
448 async fn plain_member_cannot_rename() {
449 let db = test::db().await;
450 let services = Services::default();
451 let owner = signed_in("Owner", &db).await;
452 let member = signed_in("Member", &db).await;
453 let community = call(
454 CreateCommunity {
455 name: "The Community".to_string(),
456 },
457 &owner,
458 &db,
459 &services,
460 )
461 .await
462 .unwrap();
463 invite_and_accept(community.id, &owner, &member, "Member", &db, &services).await;
464
465 let response = call(
466 UpdateCommunity {
467 community_id: community.id,
468 name: "Renamed".to_string(),
469 },
470 &member,
471 &db,
472 &services,
473 )
474 .await;
475
476 assert!(matches!(response, Err(CommonError::Forbidden)));
477 }
478
479 #[tokio::test]
480 async fn accepted_friend_request_befriends_both() {
481 let db = test::db().await;
482 let services = Services::default();
483 let first = signed_in("First", &db).await;
484 let second = signed_in("Second", &db).await;
485 let first_user = call(
486 FindUser {
487 username: "First".to_string(),
488 },
489 &second,
490 &db,
491 &services,
492 )
493 .await
494 .unwrap();
495 let second_user = call(
496 FindUser {
497 username: "Second".to_string(),
498 },
499 &first,
500 &db,
501 &services,
502 )
503 .await
504 .unwrap();
505 call(
506 AddFriend {
507 user_id: second_user.id,
508 },
509 &first,
510 &db,
511 &services,
512 )
513 .await
514 .unwrap();
515 call(
516 AcceptFriend {
517 user_id: first_user.id,
518 },
519 &second,
520 &db,
521 &services,
522 )
523 .await
524 .unwrap();
525
526 let first_friends = call(ListFriends, &first, &db, &services).await.unwrap();
527 let second_friends = call(ListFriends, &second, &db, &services).await.unwrap();
528
529 assert_eq!(vec![second_user], first_friends.friends);
530 assert_eq!(vec![first_user], second_friends.friends);
531 }
532
533 #[tokio::test]
534 async fn invite_and_accept_makes_member() {
535 let db = test::db().await;
536 let services = Services::default();
537 let owner = signed_in("Owner", &db).await;
538 let member = signed_in("Member", &db).await;
539 let community = call(
540 CreateCommunity {
541 name: "The Community".to_string(),
542 },
543 &owner,
544 &db,
545 &services,
546 )
547 .await
548 .unwrap();
549
550 invite_and_accept(community.id, &owner, &member, "Member", &db, &services).await;
551
552 let communities = call(ListCommunities, &member, &db, &services)
553 .await
554 .unwrap();
555 assert_eq!(vec![community], communities);
556 }
557
558 #[tokio::test]
559 async fn delete_community_removes_messages() {
560 let db = test::db().await;
561 let services = Services::default();
562 let owner = signed_in("Owner", &db).await;
563 let community = call(
564 CreateCommunity {
565 name: "The Community".to_string(),
566 },
567 &owner,
568 &db,
569 &services,
570 )
571 .await
572 .unwrap();
573 call(
574 CreateMessage {
575 community_id: community.id,
576 body: "Tahinli".to_string(),
577 attachments: Vec::new(),
578 reply_to: None,
579 },
580 &owner,
581 &db,
582 &services,
583 )
584 .await
585 .unwrap();
586
587 call(
588 DeleteCommunity {
589 community_id: community.id,
590 },
591 &owner,
592 &db,
593 &services,
594 )
595 .await
596 .unwrap();
597
598 let conn = db.lock().await.unwrap();
599 let remaining = db::message::read_page(community.id, None, false, &conn)
600 .await
601 .unwrap();
602
603 assert!(remaining.is_empty());
604 }
605
606 async fn group(owner: &Arc<Client>, db: &Db, services: &Services) -> Id {
607 call(
608 CreateCommunity {
609 name: "The Community".to_string(),
610 },
611 owner,
612 db,
613 services,
614 )
615 .await
616 .unwrap()
617 .id
618 }
619
620 async fn user_id(username: &str, by: &Arc<Client>, db: &Db, services: &Services) -> Id {
621 call(
622 FindUser {
623 username: username.to_string(),
624 },
625 by,
626 db,
627 services,
628 )
629 .await
630 .unwrap()
631 .id
632 }
633
634 #[tokio::test]
635 async fn kick_of_non_member_is_not_found() {
636 let db = test::db().await;
637 let services = Services::default();
638 let owner = signed_in("Owner", &db).await;
639 signed_in("Outsider", &db).await;
640 let community_id = group(&owner, &db, &services).await;
641 let outsider = user_id("Outsider", &owner, &db, &services).await;
642
643 let kick = Kick {
644 community_id,
645 user_id: outsider,
646 reason: None,
647 };
648
649 assert!(matches!(
650 call(kick, &owner, &db, &services).await,
651 Err(CommonError::NotFound)
652 ));
653 }
654
655 #[tokio::test]
656 async fn builder_cannot_leave_owned_group() {
657 let db = test::db().await;
658 let services = Services::default();
659 let builder = signed_in_as("Builder", Role::Builder, &db).await;
660 let community_id = group(&builder, &db, &services).await;
661
662 let leave = LeaveCommunity { community_id };
663
664 assert!(matches!(
665 call(leave, &builder, &db, &services).await,
666 Err(CommonError::Forbidden)
667 ));
668 }
669}