Skip to main content

tuwunel_service/rooms/state_accessor/
mod.rs

1//! Reads room-state snapshots and evaluates state-based access policy.
2//!
3//! The service resolves current and historical state into typed events. It also
4//! centralizes visibility, redaction, erasure, invite, and tombstone decisions.
5
6mod checked;
7mod erased;
8mod room_state;
9mod server_can;
10mod state;
11mod user_can;
12
13use std::sync::Arc;
14
15use async_trait::async_trait;
16use futures::{FutureExt, TryFutureExt, future::try_join};
17use ruma::{
18	EventEncryptionAlgorithm, OwnedRoomAliasId, RoomId, UserId,
19	events::{
20		StateEventType,
21		room::{
22			avatar::RoomAvatarEventContent,
23			canonical_alias::RoomCanonicalAliasEventContent,
24			create::RoomCreateEventContent,
25			encryption::RoomEncryptionEventContent,
26			guest_access::{GuestAccess, RoomGuestAccessEventContent},
27			history_visibility::HistoryVisibility,
28			join_rules::{JoinRule, RoomJoinRulesEventContent},
29			member::RoomMemberEventContent,
30			name::RoomNameEventContent,
31			power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent},
32			topic::RoomTopicEventContent,
33		},
34	},
35	room::RoomType,
36};
37use tuwunel_core::{
38	Result, err, implement,
39	utils::{BoolExt, OptionExt},
40};
41use tuwunel_matrix::{
42	Event, Pdu, room::state::resolution::events::RoomCreateEvent, room_version,
43};
44
45use crate::rooms::{state_compressor::CompressedState, timeline::Mapped};
46
47/// Resolves room state and answers state-based authorization questions.
48///
49/// Accessors share the state, timeline, short-ID, and membership services so
50/// callers use one interpretation of current and historical room state.
51pub struct Service {
52	services: Arc<crate::services::OnceServices>,
53}
54
55#[async_trait]
56impl crate::Service for Service {
57	fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
58		Ok(Arc::new(Self { services: args.services.clone() }))
59	}
60
61	fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
62}
63
64impl Service {
65	/// Returns the effective power levels for a room.
66	///
67	/// A missing or invalid `m.room.power_levels` event falls back to the room
68	/// version's defaults. The create event and its room-version rules are required.
69	pub async fn get_power_levels(&self, room_id: &RoomId) -> Result<RoomPowerLevels> {
70		let create = self.get_create(room_id);
71		let power_levels = self
72			.room_state_get_content(room_id, &StateEventType::RoomPowerLevels, "")
73			.map_ok(|c: RoomPowerLevelsEventContent| c)
74			.map(Result::ok)
75			.map(Ok);
76
77		let (create, power_levels) = try_join(create, power_levels).await?;
78
79		let room_version = create.room_version()?;
80		let rules = room_version::rules(&room_version)?;
81		let creators = create.creators(&rules.authorization)?;
82
83		Ok(RoomPowerLevels::new(power_levels.into(), &rules.authorization, creators))
84	}
85
86	/// Returns the room's current create event wrapper.
87	///
88	/// The lookup uses the empty state key and returns an error when the event or
89	/// its state snapshot cannot be resolved.
90	pub async fn get_create(&self, room_id: &RoomId) -> Result<RoomCreateEvent<Pdu>> {
91		self.room_state_get(room_id, &StateEventType::RoomCreate, "")
92			.await
93			.map(RoomCreateEvent::new)
94	}
95
96	/// Returns the room's current non-empty name.
97	///
98	/// Missing, invalid, and empty `m.room.name` content is reported as an error.
99	pub async fn get_name(&self, room_id: &RoomId) -> Result<String> {
100		self.room_state_get_content(room_id, &StateEventType::RoomName, "")
101			.await
102			.and_then(|c: RoomNameEventContent| {
103				c.name
104					.is_empty()
105					.is_false()
106					.then_some(c.name)
107					.ok_or_else(|| err!(Request(NotFound("Empty name found in event content."))))
108			})
109	}
110
111	/// Returns the room's current avatar content.
112	///
113	/// Missing or invalid `m.room.avatar` state is returned as an error.
114	pub async fn get_avatar(&self, room_id: &RoomId) -> Result<RoomAvatarEventContent> {
115		self.room_state_get_content(room_id, &StateEventType::RoomAvatar, "")
116			.await
117	}
118
119	/// Returns a user's current membership event content in a room.
120	///
121	/// The user ID is used as the membership state key. Missing or invalid state
122	/// is returned as an error.
123	pub async fn get_member(
124		&self,
125		room_id: &RoomId,
126		user_id: &UserId,
127	) -> Result<RoomMemberEventContent> {
128		self.room_state_get_content(room_id, &StateEventType::RoomMember, user_id.as_str())
129			.await
130	}
131
132	/// Reports whether the room is world-readable.
133	///
134	/// Missing, unreadable, or invalid history-visibility state is treated as not
135	/// world-readable.
136	pub async fn is_world_readable(&self, room_id: &RoomId) -> bool {
137		self.get_history_visibility(room_id).await == HistoryVisibility::WorldReadable
138	}
139
140	/// Returns the room's current history visibility.
141	///
142	/// Falls back to [`HistoryVisibility::Shared`] when the room has no current
143	/// state or its history-visibility state is missing, unreadable, or invalid.
144	pub async fn get_history_visibility(&self, room_id: &RoomId) -> HistoryVisibility {
145		self.services
146			.state
147			.get_room_shortstatehash(room_id)
148			.await
149			.ok()
150			.map_async(|shortstatehash| self.history_visibility(shortstatehash))
151			.await
152			.unwrap_or(HistoryVisibility::Shared)
153	}
154
155	/// Reports whether guest users may join the room.
156	///
157	/// Missing, unreadable, or invalid guest-access state is treated as denying
158	/// guest joins.
159	pub async fn guest_can_join(&self, room_id: &RoomId) -> bool {
160		self.room_state_get_content(room_id, &StateEventType::RoomGuestAccess, "")
161			.await
162			.map(|c: RoomGuestAccessEventContent| c.guest_access == GuestAccess::CanJoin)
163			.unwrap_or(false)
164	}
165
166	/// Returns the room's current primary canonical alias.
167	///
168	/// Alternate aliases are not considered. Missing state, invalid content, or
169	/// an absent primary alias is returned as an error.
170	pub async fn get_canonical_alias(&self, room_id: &RoomId) -> Result<OwnedRoomAliasId> {
171		self.room_state_get_content(room_id, &StateEventType::RoomCanonicalAlias, "")
172			.await
173			.and_then(|c: RoomCanonicalAliasEventContent| {
174				c.alias
175					.ok_or_else(|| err!(Request(NotFound("No alias found in event content."))))
176			})
177	}
178
179	/// Returns the room's current plain-text topic.
180	///
181	/// Rich-topic plain text takes precedence over the legacy field. Missing,
182	/// invalid, or empty topic content is returned as an error.
183	pub async fn get_room_topic(&self, room_id: &RoomId) -> Result<String> {
184		self.room_state_get_content(room_id, &StateEventType::RoomTopic, "")
185			.await
186			.and_then(|content: RoomTopicEventContent| {
187				plain_text_topic(content)
188					.ok_or_else(|| err!(Request(NotFound("Empty topic found in event content."))))
189			})
190	}
191
192	/// Returns the room's current join rule.
193	///
194	/// Any missing, unreadable, or invalid join-rules state falls back to
195	/// [`JoinRule::Invite`].
196	pub async fn get_join_rules(&self, room_id: &RoomId) -> JoinRule {
197		self.room_state_get_content(room_id, &StateEventType::RoomJoinRules, "")
198			.await
199			.map_or(JoinRule::Invite, |c: RoomJoinRulesEventContent| c.join_rule)
200	}
201
202	/// Returns the room type declared by the current create event.
203	///
204	/// A missing create event, invalid content, or absent room type is returned as
205	/// an error; ordinary rooms therefore do not yield a synthetic type.
206	pub async fn get_room_type(&self, room_id: &RoomId) -> Result<RoomType> {
207		self.room_state_get_content(room_id, &StateEventType::RoomCreate, "")
208			.await
209			.and_then(|content: RoomCreateEventContent| {
210				content
211					.room_type
212					.ok_or_else(|| err!(Request(NotFound("No type found in event content"))))
213			})
214	}
215
216	/// Returns the room's configured encryption algorithm.
217	///
218	/// Missing or invalid `m.room.encryption` state is returned as an error.
219	pub async fn get_room_encryption(
220		&self,
221		room_id: &RoomId,
222	) -> Result<EventEncryptionAlgorithm> {
223		self.room_state_get_content(room_id, &StateEventType::RoomEncryption, "")
224			.await
225			.map(|content: RoomEncryptionEventContent| content.algorithm)
226	}
227
228	/// Reports whether an encryption state event is present.
229	///
230	/// This checks that the event can be loaded, but does not deserialize its
231	/// content or validate an encryption algorithm.
232	pub async fn is_encrypted_room(&self, room_id: &RoomId) -> bool {
233		self.room_state_get(room_id, &StateEventType::RoomEncryption, "")
234			.await
235			.is_ok()
236	}
237}
238
239/// Returns a user's membership content in a room's current state, as
240/// [`Service::get_member`] does, given that state rebuilt by
241/// `room_state_checked`.
242///
243/// Every outcome is the one that function gives, except that damage from the
244/// member's short ids to the event's timeline mapping is `Mapped::Damaged` where
245/// that function panics, fails or reads a prefix, and a failed read keeps its own
246/// error. Integrity checks read members through here, rebuilding a room's state
247/// once for all of its members.
248#[implement(Service)]
249pub(crate) async fn get_member_checked(
250	&self,
251	state: &CompressedState,
252	user_id: &UserId,
253) -> Result<Mapped<RoomMemberEventContent>> {
254	let event_id = self
255		.state_get_id_checked(state, &StateEventType::RoomMember, user_id.as_str())
256		.await?;
257
258	let Mapped::Event(event_id) = event_id else {
259		return Ok(Mapped::Damaged);
260	};
261
262	let member: Mapped<Pdu> = self
263		.services
264		.timeline
265		.get_checked(&event_id)
266		.await?;
267
268	match member {
269		| Mapped::Event(member) => member.get_content().map(Mapped::Event),
270		| Mapped::Damaged => Ok(Mapped::Damaged),
271	}
272}
273
274/// Checks whether the room federates, per `m.federate` in its create event.
275///
276/// An absent `m.federate` means the room federates, which is the spec
277/// default. A missing or unparsable create event reports the same, so a
278/// failed read never reports a room as non-federating.
279#[implement(Service)]
280pub async fn is_federating(&self, room_id: &RoomId) -> bool {
281	self.get_create(room_id)
282		.await
283		.and_then(|create| create.federate())
284		.unwrap_or(true)
285}
286
287/// Resolves room-topic content to a non-empty plain-text rendering.
288///
289/// The `m.topic` block's `text/plain` representation takes precedence under
290/// MSC3765, followed by the legacy `topic` field. Empty values yield `None`.
291pub(crate) fn plain_text_topic(content: RoomTopicEventContent) -> Option<String> {
292	let topic = content
293		.topic_block
294		.text
295		.find_plain()
296		.map(ToOwned::to_owned)
297		.unwrap_or(content.topic);
298
299	topic.is_empty().is_false().then_some(topic)
300}