tuwunel_service/rooms/state_accessor/
user_can.rs1use futures::TryFutureExt;
8use ruma::{
9 EventId, RoomId, UserId,
10 events::{
11 StateEventType, TimelineEventType,
12 room::{
13 history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
14 member::{MembershipState, RoomMemberEventContent},
15 tombstone::RoomTombstoneEventContent,
16 },
17 },
18};
19use tuwunel_core::{
20 Err, Result, err, implement,
21 utils::{BoolExt, FutureBoolExt, OptionExt, future::TryExtExt, result::NotFound},
22};
23use tuwunel_matrix::{Event, PduCount, StateKey, pdu::PduBuilder};
24
25use crate::rooms::{short::ShortStateHash, state::RoomMutexGuard};
26
27#[implement(super::Service)]
34pub async fn user_can_redact(
35 &self,
36 redacts: &EventId,
37 sender: &UserId,
38 room_id: &RoomId,
39 federation: bool,
40) -> Result<bool> {
41 let redacting_event = self.services.timeline.get_pdu(redacts).await;
42
43 if redacting_event
44 .as_ref()
45 .is_ok_and(|pdu| pdu.room_id() != room_id)
46 {
47 return Ok(false);
48 }
49
50 if redacting_event
51 .as_ref()
52 .is_ok_and(|pdu| *pdu.kind() == TimelineEventType::RoomCreate)
53 {
54 return Err!(Request(Forbidden("Redacting m.room.create is not safe, forbidding.")));
55 }
56
57 if redacting_event
58 .as_ref()
59 .is_ok_and(|pdu| *pdu.kind() == TimelineEventType::RoomServerAcl)
60 {
61 return Err!(Request(Forbidden(
62 "Redacting m.room.server_acl will result in the room being inaccessible for \
63 everyone (empty allow key), forbidding."
64 )));
65 }
66
67 match self.get_power_levels(room_id).await {
68 | Ok(power_levels) => Ok(power_levels.user_can_redact_event_of_other(sender)
69 || power_levels.user_can_redact_own_event(sender)
70 && match redacting_event {
71 | Ok(redacting_event) =>
72 if federation {
73 redacting_event.sender().server_name() == sender.server_name()
74 } else {
75 redacting_event.sender() == sender
76 },
77 | _ => false,
78 }),
79 | _ => {
80 match self
82 .room_state_get(room_id, &StateEventType::RoomCreate, "")
83 .await
84 {
85 | Ok(room_create) => Ok(room_create.sender() == sender
86 || redacting_event
87 .as_ref()
88 .is_ok_and(|redacting_event| redacting_event.sender() == sender)),
89 | _ => Err!(Database(
90 "No m.room.power_levels or m.room.create events in database for room"
91 )),
92 }
93 },
94 }
95}
96
97#[implement(super::Service)]
108#[tracing::instrument(skip_all, level = "trace")]
109pub async fn user_can_see_event<Pdu>(&self, user_id: &UserId, pdu: &Pdu) -> bool
110where
111 Pdu: Event,
112{
113 let room_id = pdu.room_id();
114 let Ok(shortstatehash) = self
115 .services
116 .state
117 .pdu_shortstatehash(pdu.event_id())
118 .or_else(async |error| {
119 if !error.is_not_found() {
121 return Err(error);
122 }
123
124 self.services
125 .state
126 .get_room_shortstatehash(room_id)
127 .await
128 })
129 .await
130 else {
131 return false;
132 };
133
134 match self.history_visibility(shortstatehash).await {
135 | HistoryVisibility::WorldReadable => true,
136
137 | HistoryVisibility::Invited =>
139 matches!(
140 pdu.membership_for(user_id),
141 Some(MembershipState::Join | MembershipState::Invite)
142 ) || self
143 .user_was_invited(shortstatehash, user_id)
144 .await,
145
146 | HistoryVisibility::Joined =>
148 matches!(pdu.membership_for(user_id), Some(MembershipState::Join))
149 || self
150 .user_was_joined(shortstatehash, user_id)
151 .await,
152
153 | HistoryVisibility::Shared | _ =>
155 self.user_shared_history(shortstatehash, room_id, pdu.event_id(), user_id)
156 .await,
157 }
158}
159
160#[implement(super::Service)]
166async fn user_shared_history(
167 &self,
168 shortstatehash: ShortStateHash,
169 room_id: &RoomId,
170 event_id: &EventId,
171 user_id: &UserId,
172) -> bool {
173 let state_cache = &self.services.state_cache;
174
175 if state_cache.is_joined(user_id, room_id).await
176 || self
177 .user_was_joined(shortstatehash, user_id)
178 .await
179 {
180 return true;
181 }
182
183 if !state_cache.once_joined(user_id, room_id).await {
184 return false;
185 }
186
187 let Ok(left_count) = state_cache.get_left_count(room_id, user_id).await else {
188 return false;
189 };
190
191 let Ok(event_count) = self
192 .services
193 .timeline
194 .get_pdu_count(event_id)
195 .await
196 else {
197 return false;
198 };
199
200 event_count <= PduCount::from_unsigned(left_count)
201}
202
203#[implement(super::Service)]
209#[tracing::instrument(skip_all, level = "trace")]
210pub async fn user_can_see_state_events(&self, user_id: &UserId, room_id: &RoomId) -> bool {
211 self.user_can_see_current_state(user_id, room_id)
212 .await
213 || self.is_departed_member(user_id, room_id).await
214}
215
216#[implement(super::Service)]
222async fn user_can_see_current_state(&self, user_id: &UserId, room_id: &RoomId) -> bool {
223 if self
224 .services
225 .state_cache
226 .is_joined(user_id, room_id)
227 .await
228 {
229 return true;
230 }
231
232 match self.get_history_visibility(room_id).await {
233 | HistoryVisibility::WorldReadable => true,
234 | HistoryVisibility::Invited =>
235 self.services
236 .state_cache
237 .is_invited(user_id, room_id)
238 .await,
239 | _ => false,
240 }
241}
242
243#[implement(super::Service)]
249async fn is_departed_member(&self, user_id: &UserId, room_id: &RoomId) -> bool {
250 let state_cache = &self.services.state_cache;
251
252 state_cache
253 .get_left_count(room_id, user_id)
254 .is_ok()
255 .and(state_cache.once_joined(user_id, room_id))
256 .await
257}
258
259#[implement(super::Service)]
266#[tracing::instrument(skip(self), level = "debug")]
267pub async fn user_visible_shortstatehash(
268 &self,
269 user_id: &UserId,
270 room_id: &RoomId,
271 at: Option<PduCount>,
272) -> Result<Option<ShortStateHash>> {
273 let departure = self.departure_count(user_id, room_id).await?;
274
275 match (departure, at) {
276 | (Some(departure), _) if at.is_none_or(|at| departure <= at) =>
277 self.departure_shortstatehash(room_id, departure)
278 .map_ok(Some)
279 .await,
280
281 | (None, _)
282 if !self
283 .user_can_see_current_state(user_id, room_id)
284 .await =>
285 Ok(None),
286
287 | (_, Some(at)) =>
288 self.services
289 .timeline
290 .shortstatehash_after(room_id, at)
291 .map_ok(Some)
292 .await,
293
294 | (_, None) =>
295 self.services
296 .state
297 .get_room_shortstatehash(room_id)
298 .map_ok(Some)
299 .map_err(|e| err!(Database("Missing state for {room_id:?}: {e:?}")))
300 .await,
301 }
302}
303
304#[implement(super::Service)]
312#[tracing::instrument(skip(self), level = "debug")]
313pub async fn departure_count(
314 &self,
315 user_id: &UserId,
316 room_id: &RoomId,
317) -> Result<Option<PduCount>> {
318 let state_cache = &self.services.state_cache;
319
320 if state_cache.is_joined(user_id, room_id).await
321 || !state_cache.once_joined(user_id, room_id).await
322 {
323 return Ok(None);
324 }
325
326 let Some(left_count) = state_cache
328 .get_left_count(room_id, user_id)
329 .map_ok(PduCount::from_unsigned)
330 .await
331 .optional()?
332 else {
333 return Ok(None);
334 };
335
336 self.departure_event_count(user_id, room_id)
337 .map_ok(|event_count| event_count.into_iter().chain([left_count]).min())
338 .await
339}
340
341#[implement(super::Service)]
346#[tracing::instrument(skip(self), level = "debug")]
347async fn departure_event_count(
348 &self,
349 user_id: &UserId,
350 room_id: &RoomId,
351) -> Result<Option<PduCount>> {
352 let Some(member) = self
353 .room_state_get(room_id, &StateEventType::RoomMember, user_id.as_str())
354 .await
355 .optional()?
356 else {
357 return Ok(None);
358 };
359
360 let content: RoomMemberEventContent = member.get_content()?;
361
362 if !matches!(content.membership, MembershipState::Leave | MembershipState::Ban) {
363 return Ok(None);
364 }
365
366 self.services
367 .timeline
368 .get_pdu_count(member.event_id())
369 .await
370 .optional()
371}
372
373#[implement(super::Service)]
384#[tracing::instrument(skip(self), level = "debug")]
385pub async fn departure_shortstatehash(
386 &self,
387 room_id: &RoomId,
388 departure: PduCount,
389) -> Result<ShortStateHash> {
390 let after_event = self
391 .services
392 .db
393 .is_read_only()
394 .is_false()
395 .then_async(|| {
396 self.services
397 .timeline
398 .get_pdu_at(room_id, departure)
399 .and_then(async |pdu| {
400 self.services
401 .state
402 .shortstatehash_after_event(&pdu)
403 .await
404 })
405 })
406 .await
407 .transpose()
408 .optional()?
409 .flatten();
410
411 let Some(shortstatehash) = after_event else {
412 return self
413 .services
414 .timeline
415 .shortstatehash_after(room_id, departure)
416 .await;
417 };
418
419 Ok(shortstatehash)
420}
421
422#[implement(super::Service)]
428pub async fn user_can_see_room(&self, user_id: &UserId, room_id: &RoomId) -> bool {
429 let state_cache = &self.services.state_cache;
430 let joined = state_cache.is_joined(user_id, room_id);
431 let invited = state_cache.is_invited(user_id, room_id);
432 let left = state_cache.is_left(user_id, room_id);
433 let world_readable = self.is_world_readable(room_id);
434
435 joined.or3(invited, left, world_readable).await
436}
437
438#[implement(super::Service)]
444#[tracing::instrument(skip_all, level = "trace")]
445pub async fn user_can_peek(&self, user_id: &UserId, room_id: &RoomId) -> bool {
446 self.services
448 .state_cache
449 .is_joined(user_id, room_id)
450 .await
451 || self.is_world_readable(room_id).await
452}
453
454#[implement(super::Service)]
460#[tracing::instrument(skip_all, level = "trace")]
461pub async fn is_world_readable_at<Pdu>(&self, pdu: &Pdu) -> bool
462where
463 Pdu: Event,
464{
465 let opens_history = pdu.is_type_and_state_key(&TimelineEventType::RoomHistoryVisibility, "")
466 && pdu
467 .get_content()
468 .is_ok_and(|c: RoomHistoryVisibilityEventContent| {
469 c.history_visibility == HistoryVisibility::WorldReadable
470 });
471
472 opens_history
473 || self.history_visibility_at(pdu.event_id()).await
474 == Some(HistoryVisibility::WorldReadable)
475}
476
477#[implement(super::Service)]
482#[tracing::instrument(skip_all, level = "trace")]
483async fn history_visibility_at(&self, event_id: &EventId) -> Option<HistoryVisibility> {
484 self.services
485 .state
486 .pdu_shortstatehash(event_id)
487 .await
488 .ok()
489 .map_async(|shortstatehash| self.history_visibility(shortstatehash))
490 .await
491}
492
493#[implement(super::Service)]
499pub async fn user_can_invite(
500 &self,
501 room_id: &RoomId,
502 sender: &UserId,
503 target_user: &UserId,
504 state_lock: &RoomMutexGuard,
505) -> bool {
506 self.services
507 .timeline
508 .create_hash_and_sign_event(
509 PduBuilder::state(
510 target_user.as_str(),
511 &RoomMemberEventContent::new(MembershipState::Invite),
512 ),
513 sender,
514 room_id,
515 state_lock,
516 )
517 .await
518 .is_ok()
519}
520
521#[implement(super::Service)]
527pub async fn user_can_tombstone(
528 &self,
529 room_id: &RoomId,
530 user_id: &UserId,
531 state_lock: &RoomMutexGuard,
532) -> bool {
533 if !self
534 .services
535 .state_cache
536 .is_joined(user_id, room_id)
537 .await
538 {
539 return false;
540 }
541
542 self.services
543 .timeline
544 .create_hash_and_sign_event(
545 PduBuilder::state(StateKey::new(), &RoomTombstoneEventContent {
546 replacement_room: room_id.into(), body: "Not a valid m.room.tombstone.".into(),
548 }),
549 user_id,
550 room_id,
551 state_lock,
552 )
553 .await
554 .is_ok()
555}
556
557#[cfg(test)]
558mod tests;