Skip to main content

tuwunel_service/rooms/state_accessor/
user_can.rs

1//! Evaluates user visibility and event-authoring permissions.
2//!
3//! Historical visibility checks combine event-time state with retained
4//! membership metadata. Invite and tombstone checks use the normal event-build
5//! pipeline as non-persisting authorization probes.
6
7use 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/// Reports whether a user may redact an event in a room.
28///
29/// Cross-room targets are denied, while create and server-ACL targets return a
30/// forbidden error. Federation permits the own-event rule for any sender on
31/// the target sender's server; power-level failures fall back to create-event
32/// ownership and exact sender equality.
33#[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			// Falling back on m.room.create to judge power level
81			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/// Reports whether a user may see an event under its historical visibility.
98///
99/// An event without recorded state, such as a room's create event or a
100/// backfilled event, is judged by the room's current state instead; it is
101/// hidden when the room has none, as it is when the event's state cannot be
102/// read. Missing or invalid history visibility defaults to `shared`, whose
103/// decision also accounts for the user's membership intervals around the
104/// event. Under `joined` and `invited`, the user's own membership event is
105/// visible when the membership it sets qualifies, per the spec's
106/// before-or-after rule.
107#[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			// Only a missing snapshot falls back, so a failed read cannot widen access.
120			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		// Allow the user's own invite or join, or a user at least invited at the event
138		| 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		// Allow the user's own join, or a user joined at the event
147		| 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		// An unrecognized value is treated as shared.
154		| HistoryVisibility::Shared | _ =>
155			self.user_shared_history(shortstatehash, room_id, pdu.event_id(), user_id)
156				.await,
157	}
158}
159
160/// Whether a user may see an event under `shared` history visibility.
161///
162/// A current member sees the whole room, which the first check answers without
163/// touching room state. A former member keeps events through their latest
164/// leave, and lookup failures deny access.
165#[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/// Reports whether a user may read the room's state events.
204///
205/// Whoever may read the current state (see `user_can_see_current_state`) is
206/// admitted, as is a departed member, who reads their departure snapshot.
207/// `user_visible_shortstatehash` makes the same decision when selecting a snapshot.
208#[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/// Reports whether a user may read the room's current state.
217///
218/// A joined user may read it, as may anyone under world-readable history and a
219/// pending invitee under invited history. Under `joined`, `shared` and any
220/// value not understood (treated as `shared` by the spec), nobody else may.
221#[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/// Reports whether a user once joined a room and keeps a departure count there.
244///
245/// This is the count `departure_count` selects the snapshot by. A leave or ban
246/// that ended only an invite or a knock, or banned a user who never joined,
247/// marks no departed member, and forgetting the room drops the count.
248#[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/// Selects the state snapshot a user may read.
260///
261/// A departed member reads the state after their departure, or after an earlier
262/// `at`; a user allowed the current state reads it, or the state after `at`.
263/// Anyone else, including a member whose departure was forgotten, reads none.
264/// Callers check access first; selection rechecks it so lapsed admission cannot widen reads.
265#[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/// Returns the timeline count at which a departed member left a room.
305///
306/// A user who once joined and keeps a leave or ban count is a departed member.
307/// The count is bounded by the leave or ban in current state, so one
308/// overwritten by a later count never reaches past the real departure. A
309/// joined user, one who never joined, or one whose count is gone because they
310/// forgot the room or were invited back, has none.
311#[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	// Sequenced, so a user whose left count is gone skips the member event read.
327	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/// Returns the timeline count of the user's leave or ban in current state.
342///
343/// There is none when the member event is absent or sets any other
344/// membership, or when the event has no timeline count.
345#[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/// Returns the snapshot after a departed member's departure.
374///
375/// The departure is the member event at the count, and the snapshot after it
376/// is the state at that event with the event applied, rather than the next
377/// timeline event's snapshot: a remote event's snapshot follows its position
378/// in the event graph, not in this timeline, so it can miss the departure or
379/// include later state. A count holding no event, such as a departure
380/// recorded by a state reset, an event without a snapshot, or a read-only
381/// database, which cannot store the derived snapshot, falls back to the
382/// snapshot preceding the next timeline event.
383#[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/// Reports whether a user may discover or inspect a room.
423///
424/// Current join, invite, retained left membership, or world-readable history
425/// grants access. Forgetting a room clears the retained left membership and can
426/// therefore remove this visibility.
427#[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/// Reports whether a user may peek into a room, as a room preview does.
439///
440/// A member always may, and anyone else only while the room's history is
441/// world-readable. Unlike `user_can_see_room`, a pending invite or a retained
442/// left membership grants nothing here.
443#[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	// Sequenced rather than raced, so a member's point get skips the state read.
447	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/// Reports whether the room's history was world-readable at an event.
455///
456/// A peek may show only such events, so an event without recorded state, or
457/// with missing or invalid history visibility, does not qualify. The event that
458/// makes the room world-readable counts as well, as the spec requires.
459#[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/// Returns the history visibility in the state an event was sent in.
478///
479/// Missing or invalid history visibility reads as `shared`, and `None` means
480/// the event's state is unrecorded or unreadable.
481#[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/// Probes whether a sender may invite a target user.
494///
495/// The normal event-build, authorization, and signing path runs under the
496/// caller's room-state lock, but the synthetic membership event is not stored.
497/// Any build error denies the invite, while build-time ID allocations may remain.
498#[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/// Probes whether a user may send a room tombstone.
522///
523/// The user must currently be joined. The normal event-build, authorization,
524/// and signing path evaluates a synthetic tombstone without storing it; any
525/// build error denies permission, while build-time ID allocations may remain.
526#[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(), // placeholder,
547				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;